Last active
November 4, 2020 10:22
-
-
Save natemoo-re/0bfe5e75b5a0616c6c025eb331382610 to your computer and use it in GitHub Desktop.
Safe(ish) Eval
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
// Adopted from Alpine.js | |
// https://github.com/alpinejs/alpine/blob/b6e07b2775de444c5f9bdc4d94accb7b720fd6a7/src/utils.js#L59 | |
function saferEval(expression, context, additionalHelperVariables = {}) { | |
return (new Function(['$data', ...Object.keys(additionalHelperVariables)], `var result; with($data) { result = ${expression} }; return result`))( | |
context, ...Object.values(additionalHelperVariables) | |
) | |
} | |
export default function sandboxedEval(expression, context = {}) { | |
const resetGlobals = Object.keys(globalThis).reduce((a,k)=>{a[k]=undefined;return a;},{}); | |
return saferEval(expression, context, resetGlobals); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment