-
Notifications
You must be signed in to change notification settings - Fork 3
/
index.js
54 lines (46 loc) · 1.27 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
;(function initHeroin() {
'use strict';
function getExpectedArguments(fn) {
var FN_ARGS = /^function\s*[^\(]*\(\s*([^\)]*)\)/m;
var text = fn.toString();
var args = text.match(FN_ARGS)[1].split(',');
args = args.map(function (name) {
return name.trim();
});
return args;
}
function heroin(obj, methodName, dependencies) {
var original;
if (typeof obj === 'function') {
original = obj;
dependencies = methodName;
} else {
original = obj[methodName];
}
dependencies = dependencies || {};
var expected = getExpectedArguments(original);
var proxy = function () {
var runtimeArgs = Array.prototype.slice.call(arguments, 0);
var parameters = expected.map(function (name) {
if (dependencies.hasOwnProperty(name)) {
return dependencies[name];
} else {
return runtimeArgs.shift();
}
});
// console.log('parameters', parameters);
return original.apply(obj, parameters);
};
if (typeof obj !== 'function') {
obj[methodName] = proxy;
}
return proxy;
}
if (typeof module === 'object') {
module.exports = heroin;
}
if (typeof window === 'object') {
/* global window: true */
window.heroin = heroin;
}
}());