Created
August 14, 2018 10:20
-
-
Save instanceofme/82f8d64f20069064d7df1b200d421439 to your computer and use it in GitHub Desktop.
ES6 proxy for scala-style _.x.y 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
class Access { | |
constructor(path = []) { | |
this.path = path; | |
} | |
// Proxy | |
get(target, prop) { | |
console.log("Packing", prop); | |
return new Proxy(target, new Access([...this.path, o => o[prop]])); | |
} | |
apply(target, thisArg, args) { | |
// Still packing | |
if (args.length === 0) { // _.a() | |
return new Proxy(target, new Access([...this.path, | |
function(o) { return o.apply(this.thisArg) }])); | |
} else if (args[0] === _) { // _.a(_) called with rest of the arguments | |
return new Proxy(target, new Access([...this.path, | |
function(o) { return o.apply(this.thisArg, this.arguments) }])); | |
} | |
// Accessing | |
this.arguments = args.slice(1); | |
this.thisArg = thisArg; | |
return this.path.reduce((o, step) => step.call(this, o), args[0]); | |
} | |
} | |
let _ = new Proxy(o => o, new Access()); | |
// Can now use (only for simple cases): | |
// array.map(_.prop1.prop2) | |
// array.map(_.func1().prop) | |
// array.map(_.func2(_).prop) (func2 will receive the other callback arguments: index, array) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment