Created
December 19, 2018 03:59
-
-
Save somarlyonks/5b3a29c46bf7a729de368b5153777609 to your computer and use it in GitHub Desktop.
A rough implemention of augularjs $inject.
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 (dependency) { | |
| this.dependency = dependency; | |
| }; | |
| function readParams(func) { | |
| const fs = func.toString() | |
| const paramsMatch = fs.match(/^function.*\((.*?)\)/) || fs.match(/(.*?)\s*\=\>/) | |
| if (!paramsMatch) throw '' | |
| const paramsStr = paramsMatch[1].replace(/[\(\)]/g, '') | |
| const params = paramsStr.split(',').map(param => param.trim()).filter(_ => _) | |
| return params | |
| } | |
| DI.prototype.inject = function (func) { | |
| const paramsPattern = readParams(func) | |
| const params = paramsPattern.map(paramName => this.dependency[paramName]) | |
| return () => func(...params) | |
| } | |
| // tests | |
| const di = new DI({ | |
| 'dep1': () => 'dep1', | |
| 'dep2': () => 'dep2', | |
| 'dep3': () => 'dep3', | |
| 'dep4': () => 'dep4' | |
| }) | |
| const f = di.inject(function (dep3, dep1, dep2) { | |
| return [dep1(), dep2(), dep3()].join(' -> ') | |
| }) | |
| console.log(f() === 'dep1 -> dep2 -> dep3') // true | |
| console.log(di.inject((dep2, dep3) => dep2() + dep3())() === 'dep2dep3') // true |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment