Created
December 9, 2015 10:18
-
-
Save stuartc/3cd6c880d32a5f763c6c to your computer and use it in GitHub Desktop.
Run generated JS expressions in a closure with dynamically injected dependencies
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
var Adaptor = { | |
foo: function(message) { | |
console.log(message); | |
}, | |
bar: function() { | |
return 'baz' | |
} | |
} | |
function getHandlers(adaptor) { | |
return Object.keys(adaptor).map(function(key) { | |
return adaptor[key] | |
}) | |
} | |
function Inject(adaptor, f) { | |
// Get the functions for all the keys in the adaptor | |
// [[Function], [Function], ...] | |
var handlers = getHandlers(adaptor) | |
// Create a new Function with arguments in order and matching the names | |
// of the adaptor. | |
// | |
// new Function('foo', 'bar', 'foo(bar())') | |
// | |
// Then call the new function with the handlers in order. | |
return new Function(Object.keys(adaptor), f) | |
.apply(null, handlers) | |
} | |
Inject(Adaptor, 'foo(bar())') | |
// bar |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment