I have a function that receives an array of numbers and operations
Ex: userEntry = [3,+,3,x,3] -> returns 12
It is a calculator that adheres to the proper order of operations, therefore multiply/divide behaves differently than addition/subtraction. I have one redundant line of code:
userEntry = calculatorOperations
.calculationSequence(operationsMD[i], indexOfOperand, userEntry);
is similar to:
userEntry = calculatorOperations
.calculationSequence(userEntry[1], indexOfOperand, userEntry);
With different behavior between operations, is it possible to remove this redundant line or is it neccesary?
function operateOnEntry(userEntry) {
//this is where the calculations occur when hitting =
const operationsMD = ['x', '/'];
let indexOfOperand;
let operation;
while (userEntry.includes('x') || userEntry.includes('/')) {
let i = 0;
if (!userEntry.includes('x')) {
i++;
}
indexOfOperand = userEntry.indexOf(operationsMD[i]);
userEntry = calculatorOperations
.calculationSequence(operationsMD[i], indexOfOperand, userEntry);
}
while (userEntry.includes('+') || userEntry.includes('-')) {
indexOfOperand = 1;
userEntry = calculatorOperations
.calculationSequence(userEntry[1], indexOfOperand, userEntry);
}
return userEntry;
}
let calculatorOperations = {
'x': (arg1, arg2) => {
return arg1 * arg2;
},
'/': (arg1, arg2) => {
return arg1 / arg2;
},
'+': (arg1, arg2) => {
return arg1 + arg2;
},
'-': (arg1, arg2) => {
return arg1 - arg2;
},
returnIndexOfEntry: (index, userEntry) => {
let arg1 = Number(userEntry[index - 1]);
let arg2 = Number(userEntry[index + 1]);
return [arg1, arg2];
},
returnSpliced: (index, newTotal, userEntry) => {
userEntry.splice((index - 1), 3, newTotal);
return userEntry;
},
calculationSequence: (operation, indexOfOperand, userEntry) => {
let getArgs = calculatorOperations.returnIndexOfEntry(indexOfOperand, userEntry);
let newTotalForEntry = calculatorOperations[operation](getArgs[0], getArgs[1]);
let newUserEntry = calculatorOperations.returnSpliced(indexOfOperand, newTotalForEntry, userEntry);
return newUserEntry;
}
};
operationsMD
seems superfluous. If ax
or/
is found inuserEntry
, well there it is. Why have a separate array for these operators - and then only these operators. \$\endgroup\$operationsMD = ['x', '/']
and then passoperationsMD = ['+', '-']
\$\endgroup\$Code Review
. FWIW indenting misalignment is most often the annoying nature of writing code blocks here. As for moving thatif
to a 1-liner, I beg mercy from the court. \$\endgroup\$