Last active
October 21, 2019 21:11
-
-
Save chrispsn/1b536c53a3b9dfdf50ead497faa97000 to your computer and use it in GitHub Desktop.
IE11-compatible version of Brian Beck's eval-in-context
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
// https://twitter.com/ua6oxa/status/1170457046153650176 | |
"use strict"; | |
function evalInContext(env, code) { | |
const | |
s = JSON.stringify, | |
locals = Object.keys(env), | |
keys = locals.map(function(k){return s(k)}), | |
values = locals.map(function(k){return env[k]}), | |
body = s("return eval(" + code + ")") | |
return eval("new Function("+keys+","+body+")").apply(this, values) | |
} | |
console.assert(3==evalInContext({a: 1, b: 2}, "a + b")) | |
try {console.log(a)} | |
catch(e) {console.log("Success! No pollution of namespace")} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment