Skip to content

Instantly share code, notes, and snippets.

@nexpr
Created January 16, 2016 16:57
Show Gist options
  • Save nexpr/fb050909d9bb6ee718fe to your computer and use it in GitHub Desktop.
Save nexpr/fb050909d9bb6ee718fe to your computer and use it in GitHub Desktop.
オーバーロードする
function overload(args, fns){
var result = null
fns.some(fn => {
if(Array.isArray(fn)){
fn = {type: fn[0], function: fn[1]}
}
if(fn.type == null || fn.type.every((reqtype, i) => typeMatch(reqtype, args[i]))){
result = fn.function(...args)
return true
}
return false
})
return result
function typeMatch(reqtype, realdata){
if(typeof reqtype === "function"){
return reqtype(realdata)
}
if(Array.isArray(reqtype)){
return reqtype.some(e => typeMatch(e, realdata))
}
if(typeof reqtype === "string"){
return typeof realdata === reqtype || (typeof window[reqtype] === "function" && realdata instanceof window[reqtype])
}
return false
}
}
function abc(){
overload(arguments, [
{
type: ["number", "number", "number", "number"],
function: (a,b,c,d) => {console.log("num4",a,b,c,d)}
},{
type: ["number", "number"],
function: (a,b) => {console.log("num2",a,b)}
},{
type: ["number", "number", "number"],
function: (a,b,c) => {console.log("num3",a,b,c)}
},{
type: ["number", "string"],
function: (a,b) => {console.log("num-str",a,b)}
},{
type: ["Object", ["string","Array"]],
function: (a,b) => {console.log("obj-(str-array)",a,b)}
},{
type: null,
function: _ => {console.log("no match")}
}
])
}
console.log("--")
abc()
console.log("--")
abc(1,2,3,4)
console.log("--")
abc(1,2)
console.log("--")
abc(1,2,3)
console.log("--")
abc(1,"abc")
console.log("--")
abc({a:1},[4,5])
console.log("--")
abc({a:1},"abc")
console.log("--")
/*
--
no match
--
num4 1 2 3 4
--
num2 1 2
--
num2 1 2
--
num-str 1 abc
--
obj-(str-array) Object {a: 1} [4, 5]
--
obj-(str-array) Object {a: 1} abc
--
*/
function x(){
return overload(arguments, [
{
type: ["string", "string", "Object", "function"],
function: fn
},{
type: ["string", "function"],
function: (a,b) => fn("", a, {}, b)
},{
type: ["string", "Object"],
function: (a,b) => fn("", a, b, _ => {})
},{
type: null,
function: _ => {console.log("引数が不正です")}
}
])
function fn(target, value, option, cb){
// なにか
}
}
function y(){
overload(arguments, [
[
["Array"],
a => fn({x: a[0], y: a[1]})
],[
["Object"],
x => fn(x)
]
])
function fn(obj){
// obj.x
// obj.y
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment