Skip to content

Instantly share code, notes, and snippets.

@adamvr
Created August 13, 2013 10:59
Show Gist options
  • Save adamvr/6220070 to your computer and use it in GitHub Desktop.
Save adamvr/6220070 to your computer and use it in GitHub Desktop.
var expr = ['random', 1000, '*', 'round'];
var calc = function (expr) {
var stack = []
, left, right;
for (var i = 0; i < expr.length; i += 1) {
var val = expr[i];
console.dir(stack);
if (!isNaN(val)) {
stack.push(val);
} else {
// 0-ary operators
if (~['random'].indexOf(val)) {
// Binary operators
} else if (~['*','/','+','-'].indexOf(val)) {
right = stack.pop();
left = stack.pop();
// Unary operators
} else if (~['sqrt', 'round'].indexOf(val)) {
left = stack.pop();
}
switch (val) {
case 'random':
stack.push(Math.random());
break;
case '*':
stack.push(left * right);
break;
case '/':
stack.push(left / right);
break;
case '+':
stack.push(left | 0 + right);
break;
case '-':
stack.push(left - right);
break;
case 'sqrt':
stack.push(Math.sqrt(left));
break;
case 'round':
stack.push(Math.round(left));
break;
default:
console.log('error');
}
}
}
return stack[0];
};
console.log(calc(expr));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment