'How would you add/subtract/multiply/divide individual elements in an array/list in javascript? [closed]

I am developing a simple javascript console calculator, and I need to implement an array/list. My current idea is to create an array with three integers/elements (which the user would fill out), then (depending on what the user wants), the first two elements would be added/subtracted/divided/multiplied, and then the last element would be separately (not dependent on the first operator) added/subtracted/divided/multiplied with the answer from the first two elements.

The current array I have looks like this:

var equfirst = ["num1", "num2", "num3"];

All the elements in the array would be provided by the user.

"num1" and "num2" would be operated on first, then "num3" (as stated earlier). Or, would there be a separate way following the order of operations where the numbers could be operated in no specific order.



Solution 1:[1]

Maybe Reverse Polish Notation can be helpful here?

RPN makes it easy to specify numbers and operators in a sequential way without ever having to use parentheses. A simple JavaScript implementation could be this:

function rpn(inps) { // Reverse Polish Notation calculator
  const st = []; // the stack
  inps.forEach(t => {
    if (t.length==0) return;
    let k = st.length - 2; // index of penultimate element on stack
    if (!isNaN(t)) st.push(+t); // a numeric value (operand)
    else switch (t) { // an operator
      case "+": st[k] += st.pop(); break;
      case "-": st[k] -= st.pop(); break;
      case "*": st[k] *= st.pop(); break;
      case "/": st[k] /= st.pop(); break;
      case "**": st[k] **= st.pop(); break;
    }
  });
  return st.pop()
}

// examples:

const inpArrs=[
  [7,4,"-",5,"*"], // (7-4)*5= 15
  [7,4,5,"*","-"], //  7- 4*5=-13
  [5,7,"+",4,"/"], // (5+7)/4=  3
  // or, something more complicated:
  // Pythagoras's theorem
  [3,3,"*",4,4,"*","+",.5,"**"] // sqrt(3²+4²)=5
 ];

console.log(inpArrs.map(rpn));

// a commented input format:
const eqn="The sum of 3, 4 and 5 in RPN is: 3 4 5 + + = ";

console.log(eqn+rpn(eqn.split(" ")));

As elements of the input array are checked to be either numeric or equal to one of a given list of operators, all other types of input are ignored. Therefore strings can be seen as "comments".

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1