Last active
February 15, 2016 14:46
-
-
Save joshblack/803749c84300436955c2 to your computer and use it in GitHub Desktop.
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
const scoped = { | |
foo: () => 'foo', | |
bar: () => 'bar', | |
baz: { a: 'b' }, | |
arr: [0] | |
}; | |
const evalify = (code, scope) => { | |
const variables = Object.keys(scope) | |
.map((name) => { | |
const value = scope[name]; | |
if (value.toString() === '[object Object]') { | |
return `const ${name} = ${JSON.stringify(value)};`; | |
} | |
if (Array.isArray(value)) { | |
return `const ${name} = ${JSON.stringify(value)};`; | |
} | |
return `const ${name} = ${value.toString()};`; | |
}); | |
const program = `'use strict'; | |
${variables.join('\n')} | |
${code} | |
`; | |
return eval(program); | |
}; | |
const result = evalify('baz.a', scoped); | |
console.log(result); // 'b' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment