-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
47 lines (45 loc) · 1.29 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
function depends(a, b, list, path = []) {
if(!list[a]) return;
path = path.concat([a]);
var dep = list[a];
if(dep.dependencies.indexOf(b) !== -1) return path.concat([b]);
return dep.dependencies
.reduce((found, dep) => found ? found : depends(dep, b, list, path), null);
}
class Container {
constructor(parent) {
this.parent = parent;
this.factories = {};
}
register(name, dependencies, factory) {
if(typeof dependencies == 'function') {
factory = dependencies;
dependencies = [];
}
this.factories[name] = {
dependencies: dependencies,
factory: factory
};
var path;
if(path = depends(name, name, this.factories)) {
throw new Error(name + ' depends on itself! (' + path.join('->') +')');
}
}
resolve(name) {
if(!this.factories[name] && !this.parent) {
throw new Error('Dependency ' + name + ' not found!');
} else if(!this.factories[name]) {
return this.parent.resolve(name);
}
return this.factories[name].instance
? this.factories[name].instance
: this.factories[name].instance = this.create(name);
}
create(name) {
return this.factories[name].factory.apply(
null,
this.factories[name].dependencies.map(dep => this.resolve(dep))
);
}
}
export default Container;