Skip to content

Instantly share code, notes, and snippets.

@bluurn
Last active February 13, 2019 14:14
Show Gist options
  • Save bluurn/dad03721fba9027e489f3df781b6b2f3 to your computer and use it in GitHub Desktop.
Save bluurn/dad03721fba9027e489f3df781b6b2f3 to your computer and use it in GitHub Desktop.
JS: Implement DI
/**
* Constructor DependencyInjector
* @param {Object} - object with dependencies
*/
var DI = function (dependency) {
this.dependency = dependency;
};
// Should return new function with resolved dependencies
DI.prototype.inject = function (func) {
const deps = func
.toString()
.match(/^function \((.*)\)/)[1]
.split(',')
.map((it) =>
this.dependency[it.trim()]
)
.filter((it) => it !== undefined);
if(deps.length === 0) {
return func;
}
return () => func(...deps);
}
var deps = {
'dep1': function () {return 'this is dep1';},
'dep2': function () {return 'this is dep2';},
'dep3': function () {return 'this is dep3';},
'dep4': function () {return 'this is dep4';}
};
var di = new DI(deps);
var myFunc = di.inject(function (dep3, dep1, dep2) {
return [dep1(), dep2(), dep3()].join(' -> ');
});
Test.assertEquals(myFunc(), 'this is dep1 -> this is dep2 -> this is dep3');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment