Skip to content

Instantly share code, notes, and snippets.

@joshblack
Last active February 15, 2016 14:46
Show Gist options
  • Save joshblack/803749c84300436955c2 to your computer and use it in GitHub Desktop.
Save joshblack/803749c84300436955c2 to your computer and use it in GitHub Desktop.
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