Skip to content

Instantly share code, notes, and snippets.

@natemoo-re
Last active November 4, 2020 10:22
Show Gist options
  • Save natemoo-re/0bfe5e75b5a0616c6c025eb331382610 to your computer and use it in GitHub Desktop.
Save natemoo-re/0bfe5e75b5a0616c6c025eb331382610 to your computer and use it in GitHub Desktop.
Safe(ish) Eval
// 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