Skip to content

Instantly share code, notes, and snippets.

@ermouth
Created May 16, 2015 10:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ermouth/61cab64ffc7cb5578238 to your computer and use it in GitHub Desktop.
Save ermouth/61cab64ffc7cb5578238 to your computer and use it in GitHub Desktop.
Polish notation expression eval
var polish = (function () {
var ops = ['*','/','+','-']
.reduce( function(a, b){
a[b] = Function ( 'x', 'return x[0]=x.shift()' + b + 'x[0], x' );
return a;
}, {});
Object.getOwnPropertyNames(Math)
.forEach( function(b){
var l = Math[b].length, f = '';
if (l === void 0) f = 'x.unshift(Math.' + b + '), x';
else if (l === 0) f = 'x.unshift(Math.' + b + '()), x';
else if (l === 1) f = 'x[0]=Math.' + b + '(x[0]), x';
else if (l === 2) f = 'x[0]=Math.' + b + '(x.shift(),x[0]), x';
ops[b] = Function ( 'x', 'return ' + f);
});
return function(s) {
return s.split(/\s+/)
.reduce( function (a, b) {
if (ops[b]) ops[b](a);
else if (!isNaN(b) && b!='') a.unshift(+b);
return a;
}, []);
};
})();
// polish ("1 2 3 + + sin");
/* ES 6 basic
var polish = (function () {
var ops = "+-/*".split("").reduce((a,b)=>(a[b]=Function("x","return x[0]=x.shift()"+b+"x[0],x"),a),{});
return (s)=>s.split(/\s+/).reduce((a,b)=>(ops[b]?ops[b](a):!isNaN(b)&&b!=''?(a.unshift(+b),a):a),[]);
})();
polish("1 2 3 + +")
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment