Skip to content

Instantly share code, notes, and snippets.

@joshuakemmerling
Last active May 25, 2018 07:04
Show Gist options
  • Save joshuakemmerling/09676bdf4732d7736124ff6ee4b63af0 to your computer and use it in GitHub Desktop.
Save joshuakemmerling/09676bdf4732d7736124ff6ee4b63af0 to your computer and use it in GitHub Desktop.
Dependency injection
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)
}
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