Last active
June 10, 2017 17:40
-
-
Save 2bbb/72c2d9449428d87b9a6fe5923aec11c5 to your computer and use it in GitHub Desktop.
overloadable_function
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function fun(org = function(...args) { throw new Error("overload failed", args.map(a => typeof a)); }, ... others) { | |
const overload_functions = {}; | |
if(others.length) { | |
overload_functions[others.map(a => a.constructor.name)] = org; | |
org = function(...args) { throw new Error("overload failed", args.map(a => typeof a)); }; | |
} | |
const f = function(... args) { | |
return ((overload_functions[args.map(a => a.constructor.name)] || org).bind(this))(... args); | |
} | |
f.overload = function(overloading_function, ...args) { | |
overload_functions[args.map(a => a.constructor.name)] = overloading_function; | |
return f; | |
}; | |
return f; | |
} | |
class Obj {}; | |
class Other {}; | |
const f = fun() | |
.overload(function(p) { | |
console.log("A:", p); | |
}, 0) | |
.overload(function(p, q, r) { | |
console.log("B:", p, q, r); | |
}, "", 0, new Obj()) | |
.overload(function(p, q, r) { | |
console.log("C:", p, q, r); | |
}, "", 0, new Other()); | |
try { | |
f(); | |
} catch(e) { | |
console.log(e.message); | |
} | |
f(4); | |
f("hoge", 3, new Obj()); | |
f("hoge", 3, new Other()); | |
try { | |
f(1, 2, 3); | |
} catch(e) { | |
console.log(e.message); | |
} | |
const g = { | |
f: fun(function() { console.log(this.name); }) | |
.overload(function(name) { console.log(this.name, name); }, ""), | |
name: "hoge" | |
}; | |
g.f(); | |
g.f(1, 2, 3); | |
g.f("fuge"); | |
const h = { | |
name: "bar", | |
f: g.f, | |
}; | |
h.f(); | |
h.f("fuge"); | |
class Foo { | |
constructor() { | |
} | |
f(p) { console.log("default"); } | |
}; | |
Foo.prototype.f = fun(Foo.prototype.f, "").overload(function(x) { console.log("number", x); }, 0); | |
foo = new Foo(); | |
foo.f(""); | |
foo.f(1); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment