Skip to content

Instantly share code, notes, and snippets.

@andykais
Last active December 7, 2018 22:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save andykais/6d98e5d2d0cb591347defd3982fb191d to your computer and use it in GitHub Desktop.
Save andykais/6d98e5d2d0cb591347defd3982fb191d to your computer and use it in GitHub Desktop.
// index.js
const objectPath = Symbol("object-path");
const objectCrawler = Symbol("object-crawler");
const handler = {
get: (object, prop) => {
if (prop === objectPath) {
return object[objectPath];
} else if (String(prop) === "Symbol(util.inspect.custom)") {
return object;
} else {
const parentKeys = object[objectPath] || [];
const keys = [...parentKeys, prop];
const callParts = getCallParts(keys);
return new Proxy(callParts, handler);
}
}
};
const getCallParts = keys => {
const callParts = arg => keys.reduce((acc, key) => acc[key], arg);
callParts[objectPath] = keys;
return callParts;
};
module.exports = new Proxy(getCallParts([]), handler);
// test.js
const _ = require("../");
const array = [1, 2, 3, 4, 5, 6].map(n => ({ n })).map(_.n);
const _parent = _.parent;
const result = _parent({ parent: 1 });
console.assert(result === 1);
const result2 = _parent.child({ parent: { child: 2 } });
console.assert(result2 === 2);
const result3 = _.parent.child({ parent: { child: 3 } });
console.assert(result3 === 3);
const result4 = _.something.else({ something: { else: 4 } });
console.assert(result4 === 4);
const result5 = _.parent({ parent: 5 });
console.assert(result5 === 5);
_ + _; // requires operator overloading
// _.method().wait; // requires undersanding which functions are called statically
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment