Skip to content

Instantly share code, notes, and snippets.

@jorendorff
Last active October 7, 2023 23:23
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jorendorff/b41433404f91c453520c to your computer and use it in GitHub Desktop.
Save jorendorff/b41433404f91c453520c to your computer and use it in GitHub Desktop.
/*
* 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