Created
May 16, 2015 10:11
-
-
Save ermouth/61cab64ffc7cb5578238 to your computer and use it in GitHub Desktop.
Polish notation expression eval
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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