Last active
May 25, 2018 07:04
-
-
Save joshuakemmerling/09676bdf4732d7736124ff6ee4b63af0 to your computer and use it in GitHub Desktop.
Dependency injection
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
var DI = function () { | |
let _deps = {} | |
this.dep = (name, func) => { _deps[name] = func } | |
this.getDep = (name) => _deps[name] | |
} | |
DI.prototype.inject = function (fn) { | |
let fnString = fn.toString().replace(/((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg, ''), | |
paramNames = fnString.split('(')[1].split(')')[0].split(',').map(v => v.trim()), | |
args = paramNames.map((x) => this.getDep(x)) | |
return () => fn.apply(null, args) | |
} |
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
var di = new DI(); | |
di.dep('dep1', function () { return 'this is dep1' }) | |
di.dep('dep2', function () { return 'this is dep2' }) | |
di.dep('dep3', function () { return 'this is dep3' }) | |
di.dep('dep4', function () { return 'this is dep4' }) | |
var myFunc = di.inject((dep3, dep1, dep2) => { | |
return [ dep1(), dep2(), dep3() ].join(' -> ') | |
}) | |
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