Created
January 10, 2012 20:18
-
-
Save rauchg/1590954 to your computer and use it in GitHub Desktop.
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
/** | |
# 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); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Good point, at first I was concerned about collisions but there aren't that many props in Math: