-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDependency-Injection.js
46 lines (39 loc) · 1.72 KB
/
Dependency-Injection.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
/*
Did you hear about Dependency Injection pattern? The main idea of this pattern is that you may have ability to pass dependencies into your function in any order and they will be resolved automatically. Take a look at this:
var myDependentFunc = inject(function (secondDepency, firstDependency) {
firstDependency();
secondDepency();
});
myDependentFunc();
As you can see we just put some variables into the function's signature and work with them as usualy. But we know nothing about where these variables are located! Let's assume that all dependencies are stored in the single hash object (for instanse 'deps') and the injector function will be sought among 'deps' properties:
var deps = {
'firstDependency': function () {return 'this is firstDependency';},
'secondDepency': function () {return 'this is secondDepency';},
};
Ok, I hope this is clear. Also, in order to setup DependencyInjector (DI) we need to specify dependency object:
var DI = function (dependency) {
this.dependency = dependency;
};
Your task is create DI.prototype.inject method that will return a new function with resolved dependencies. And don't forget about nested functions. You shouldn't handle them.
*/
// Answer:
/**
* 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) {
console.log(func.toString());
const depList =
func
.toString()
.match(/\(([^)]+)\)/)?.[1]
.split(", ") || [];
const actualDeps = depList.map((name) => {
return this.dependency[name];
});
return () => func(...actualDeps);
};