-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
93 lines (78 loc) · 2.17 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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
"use strict";
var _ = require("lodash");
var loader = require("./loader");
var Instantiator = require("./instantiator");
var modules = {};
module.exports = {
get: getInstance,
getByTag: getByTag,
register: register,
registerTransient: registerTransient,
load: loader.load,
invoke: invoke
};
function getInstance(name) {
var instantiator = new Instantiator(modules);
return instantiator.getInstance(name);
}
function getByTag(tag) {
var instances = _(modules)
.filter(function(module) {
return _.includes(module.tags, tag);
})
.map(function(module) {
return [module.name, getInstance(module.name)];
})
.fromPairs()
.value();
return instances;
}
function register(name, func) {
return registerCore(name, func, false);
}
function registerTransient(name, func) {
return registerCore(name, func, true);
}
function registerCore(name, func, transient) {
var matches = name.match(/\s*([^(\s]*)\s*(\([^)]*\))?/);
name = matches[1];
var tags = _.trim(matches[2] || "", "()").split(",");
tags = _.map(tags, function(tag) {
return tag.trim();
});
if (modules[name]) {
throw new Error("A module named '" + name + "' has already been registered!");
}
modules[name] = {
name: name,
options: {
transient: transient
},
tags: tags,
func: func
};
var end = Date.now();
}
function getFunctionName(func) {
var text = func.toString();
var space = text.indexOf(" ");
var open = text.indexOf("(");
var name = text.substring(space + 1, open);
return name || "anonymous function";
}
function invoke(func) {
// Create a transient module for this function.
var module = {
name: "simple di invoked function: " + getFunctionName(func),
options: {
transient: true
},
func: func
};
// Getting an instance of the transient module will cause 'func' to be invoked.
var instantiator = new Instantiator(modules);
var value = instantiator.instantiate(module, {
wrap_return: true
});
return value.return_value;
}