public
Last active

  • Download Gist
eq.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
 
/**
 
# eq.js: minimalistic equation evaluator.
 
eq(str, vars)
 
Features:
- evaluate variables in the `vars` object
- `str` can use any `Math` function or property: round, ceil, max, E
 
Examples:
 
eq('round(test / 2)', { test: 5 }) // 3
eq('floor(test / 2)', { test: 5 }) // 2
eq('2 + 2') // 4
eq('cos(PI)') // -1
 
Handy amongst other things for CLI node programs that accept numbers.
 
**/
 
(function (g) {
function eq (input, vars) {
try {
return eval('with(Math){with(vars || {}){' + input + '}}');
} catch (e) {
return NaN;
}
};
 
g.top ? g.eq = eq : module.exports = eq;
})(this);

Since security isn't a concern, why not just remove the requirement for the $ and use two withs? eq('round(x / 2)', { x:5 }) seems more natural to me.

Good point, at first I was concerned about collisions but there aren't that many props in Math:

Math.E                     Math.LN10                  Math.LN2                   Math.LOG10E                Math.LOG2E                 Math.PI                    Math.SQRT1_2               Math.SQRT2                 Math.abs                   Math.acos                  Math.asin                  Math.atan                  Math.atan2
Math.ceil                  Math.cos                   Math.exp                   Math.floor                 Math.log                   Math.max                   Math.min                   Math.pow                   Math.random                Math.round                 Math.sin                   Math.sqrt                  Math.tan

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.