Skip to content

Instantly share code, notes, and snippets.

@bingzer
Forked from softwarespot/evaluate.js
Created February 15, 2021 23:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bingzer/3391a38c4f4b7d6689ce42b474b54625 to your computer and use it in GitHub Desktop.
Save bingzer/3391a38c4f4b7d6689ce42b474b54625 to your computer and use it in GitHub Desktop.
Pass context to eval()
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