Skip to content

Instantly share code, notes, and snippets.

@nexpr
Created June 15, 2016 15:34
Show Gist options
  • Select an option

  • Save nexpr/40a3f4fd862d61afde724bd2228fcf48 to your computer and use it in GitHub Desktop.

Select an option

Save nexpr/40a3f4fd862d61afde724bd2228fcf48 to your computer and use it in GitHub Desktop.
proxy で undefined でもチェーンさせる
function l(val){
var fn = () => {}
fn.val = val
return new Proxy(fn, {
get: getTrap,
apply: function(target, _this, args){
if(args.length === 0){
return target.val
}
var [apply_fn, ...apply_args] = args
if(typeof apply_fn === "function"){
return l(apply_fn.call(_this, target.val, ...apply_args))
}
}
})
function getTrap(target, name){
if(name === "toString"){
return method(target.val == null
? _ => target.val
: target.val.toString.bind(target.val)
)
}else if(name === "valueOf"){
return method(target.val == null
? _ => target.val
: target.val.valueOf.bind(target.val)
)
}else if(target.val != null && (name in Object(target.val))){
var prop = target.val[name]
if(typeof prop === "function"){
return method(prop.bind(target.val))
}else{
return l(prop)
}
}else{
return l()
}
}
function method(fnval){
var fn = () => {}
fn.val = fnval
return new Proxy(fn, {
get: getTrap,
apply: function(target, _this, args){
return l(target.val(...args))
}
})
}
}
/*
l([1,2,3]).forEach(e => console.log(e))
l("abc").match(/a/)[4].a.b.c()
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment