pivot/rpn.js
ElementG9 59fe22b512 Publish current work
The work that has already been done is being published in a GitHub repo.
2019-01-12 20:13:24 -07:00

40 lines
1.3 KiB
JavaScript

var solve = (exp) => {
var stack = [];
var expression = exp.split(" ");
for(var j=0;j<expression.length;j++) {
var key = expression[j];
if(key.match(/\d/)) {
stack.push(parseInt(key));
} else if(key.match(/\w/)) {
if(Object.keys(progData).includes(key)) {
stack.push(progData[key]);
} else {
stack.push(key);
}
}
switch(key) {
case "+": // add
var opItems = stack.splice(stack.length-2,2);
var result = opItems[0]+opItems[1];
stack.push(result);
break;
case "-": // subtract
var opItems = stack.splice(stack.length-2,2);
var result = opItems[0]-opItems[1];
stack.push(result);
break;
case "*": // multiply
var opItems = stack.splice(stack.length-2,2);
var result = opItems[0]*opItems[1];
stack.push(result);
break;
case "/": // divide
var opItems = stack.splice(stack.length-2,2);
var result = opItems[0]/opItems[1];
stack.push(result);
break;
}
}
return stack;
};
module.exports = solve;