-
Notifications
You must be signed in to change notification settings - Fork 2
/
index.js
61 lines (46 loc) · 1.24 KB
/
index.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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
var argsList = require('args-list');
var DiContainer = function() {
if (!(this instanceof DiContainer)) {
return new DiContainer();
}
this.dependencies = {};
this.factories = {};
};
DiContainer.prototype = {
factory: function(name, factory) {
this.factories[name] = factory;
return this;
},
register: function(name, dependency) {
this.dependencies[name] = dependency;
return this;
},
get: function(name) {
var factory;
if (!this.dependencies[name]) {
factory = this.factories[name];
this.dependencies[name] = factory && this._inject(factory);
}
if (!this.dependencies[name]) {
throw new Error('Cannot find module: ' + name);
}
return this.dependencies[name];
},
_inject: function(factory) {
var args;
var dependencies;
if (typeof factory === 'function') {
dependencies = argsList(factory);
} else if (Array.isArray(factory)) {
dependencies = factory;
factory = dependencies.pop();
} else {
throw new Error('Unrecognized factory: ' + factory);
}
args = dependencies.map(function(dependency) {
return this.get(dependency);
}.bind(this));
return factory.apply(null, args);
}
};
module.exports = DiContainer;