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); |
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
Since security isn't a concern, why not just remove the requirement for the $ and use two
with
s?eq('round(x / 2)', { x:5 })
seems more natural to me.