Skip to content

Instantly share code, notes, and snippets.

@rauchg
Created January 10, 2012 20:18
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rauchg/1590954 to your computer and use it in GitHub Desktop.
Save rauchg/1590954 to your computer and use it in GitHub Desktop.
/**
# 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);
@marcello3d
Copy link

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.

@rauchg
Copy link
Author

rauchg commented Jan 10, 2012

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment