Skip to content

Instantly share code, notes, and snippets.

@stuartc
Created December 9, 2015 10:18
Show Gist options
  • Save stuartc/3cd6c880d32a5f763c6c to your computer and use it in GitHub Desktop.
Save stuartc/3cd6c880d32a5f763c6c to your computer and use it in GitHub Desktop.
Run generated JS expressions in a closure with dynamically injected dependencies
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