-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
69 lines (69 loc) · 2.85 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
62
63
64
65
66
67
68
69
var grom;
(function (grom) {
var DepService = (function () {
function DepService(name) {
this.name = name;
this.dependencies = [];
}
return DepService;
})();
var DependencyResolver = (function () {
function DependencyResolver() {
this.services = {};
}
DependencyResolver.prototype.add = function (name) {
this.addAndGet(name);
};
DependencyResolver.prototype.addAndGet = function (serviceName) {
if (this.services[serviceName]) {
return this.services[serviceName];
}
this.services[serviceName] = new DepService(serviceName);
//Add dependency to root element for sort function to work
if (serviceName !== DependencyResolver.ROOT_SERVICE_NAME) {
this.setDependency(DependencyResolver.ROOT_SERVICE_NAME, serviceName);
}
return this.services[serviceName];
};
DependencyResolver.prototype.setDependency = function (serviceName, dependencyName) {
var service = this.addAndGet(serviceName);
var dependency = this.addAndGet(dependencyName);
service.dependencies.push(dependency);
};
DependencyResolver.prototype.resolve = function (serviceName) {
var resolved = [];
var unresolved = [];
var service = this.services[serviceName];
if (!service) {
throw new Error('DepService ' + serviceName + ' does not exist');
}
this.recursiveResolve(service, resolved, unresolved);
return resolved.map(function (s) { return s.name; });
};
DependencyResolver.prototype.sort = function () {
var deps = this.resolve(DependencyResolver.ROOT_SERVICE_NAME);
deps.pop(); //remove DependencyResolver.ROOT_SERVICE_NAME element
return deps;
};
DependencyResolver.prototype.recursiveResolve = function (service, resolved, unresolved) {
var _this = this;
unresolved.push(service);
service.dependencies.forEach(function (sub) {
if (resolved.indexOf(sub) === -1) {
if (unresolved.indexOf(sub) !== -1) {
throw new Error('Circular reference detected: ' + service.name + ' -> ' + sub.name);
}
_this.recursiveResolve(sub, resolved, unresolved);
}
});
resolved.push(service);
unresolved.splice(unresolved.indexOf(service), 1);
};
DependencyResolver.ROOT_SERVICE_NAME = '#root#';
return DependencyResolver;
})();
grom.DependencyResolver = DependencyResolver;
})(grom || (grom = {}));
if (typeof module !== 'undefined') {
module.exports = grom.DependencyResolver;
}