-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathOverloadedFunction.js
40 lines (34 loc) · 1.02 KB
/
OverloadedFunction.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
function OverloadedFunction() {
const func = function () {
const { method } = func.methods.find(entry => OverloadedFunction.matches(arguments, entry.signature)) || {};
if (method) {
return method(...arguments);
} else {
throw new Error("No suitable method found");
}
}
Object.setPrototypeOf(func, OverloadedFunction.proto);
return func;
}
OverloadedFunction.proto = {
methods: [],
add: function (signature, method) {
this.methods.push({ signature, method });
return this;
}
}
OverloadedFunction.matches = function (args, signature) {
if (args.length !== signature.length) {
return false;
}
// Go through arguments, returning false if we find a mismatch
for (let i = 0; i < args.length; i++) {
if (args[i] == null) {
continue;
}
if (!(args[i].constructor === signature[i] || args[i] instanceof signature[i])) {
return false;
}
}
return true;
}