Last active
October 7, 2023 23:23
-
-
Save jorendorff/b41433404f91c453520c 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
/* | |
* Evaluate the expression `expr` in a scope that includes (a) the global scope; and | |
* (b) the key-value pairs in `scope`. | |
* | |
* evalInScope({a: 3, b: 4}, "a + b") ===> 7 | |
* | |
* It's up to the caller to make sure that `expr` really is a JS expression and | |
* that it doesn't do anything unwanted; and that the keys of `scope` really are JS | |
* identifiers. (That is, don't use this with a `scope` or `expr` you don't trust!) | |
*/ | |
function evalInScope(scope, expr) { | |
var keys = Object.keys(scope); | |
var values = keys.map(function (key) { return scope[key]; }); | |
var f = Function(keys.join(", "), "return (" + expr + ");"); | |
// Note that at this point you could cache the function f. | |
return f.apply(undefined, values); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment