Last active
July 28, 2023 12:56
-
-
Save softwarespot/76252a838efdcace2df1f9c724e37351 to your computer and use it in GitHub Desktop.
Pass context to eval()
This file contains hidden or 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
function evaluate(code, args = {}) { | |
// Call is used to define where "this" within the evaluated code should reference. | |
// eval does not accept the likes of eval.call(...) or eval.apply(...) and cannot | |
// be an arrow function | |
return function evaluateEval() { | |
// Create an args definition list e.g. "arg1 = this.arg1, arg2 = this.arg2" | |
const argsStr = Object.keys(args) | |
.map(key => `${key} = this.${key}`) | |
.join(','); | |
const argsDef = argsStr ? `let ${argsStr};` : ''; | |
return eval(`${argsDef}${code}`); | |
}.call(args); | |
} | |
const utils = { | |
print(...args) { | |
console.log(...args); | |
} | |
}; | |
evaluate('utils.print(2 + 3);', { | |
utils | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Does it have contxt break out??