Skip to content
Create a gist now

Instantly share code, notes, and snippets.

@rauchg /eq.js

Embed URL


Subversion checkout URL

You can clone with
Download ZIP
# eq.js: minimalistic equation evaluator.
eq(str, vars)
- evaluate variables in the `vars` object
- `str` can use any `Math` function or property: round, ceil, max, E
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.eq = eq : module.exports = eq;

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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.