Skip to content

Instantly share code, notes, and snippets.

@SparK-Cruz
Last active July 26, 2022 14:08
Show Gist options
  • Save SparK-Cruz/3d820b1e61e7be6680b14f4c988be952 to your computer and use it in GitHub Desktop.
Save SparK-Cruz/3d820b1e61e7be6680b14f4c988be952 to your computer and use it in GitHub Desktop.
Lib for chaining any method by using the ._. operator
exports.unchain = function unchain(subject) {
const proxy = new Proxy(subject, {
get(target, name, receiver) {
if (name === '_') {
return new Proxy(subject, {
get(target, name, receiver) {
const member = Reflect.get(target, name, receiver);
if (typeof member === 'function') {
return function () {
member.apply(subject, arguments);
return proxy;
};
}
return member;
}
});
}
const member = Reflect.get(target, name, receiver);
if (typeof member === 'function') {
return function () {
const value = member.apply(subject, arguments);
if (typeof value === 'object')
return unchain(value);
return value;
};
}
if (typeof member === 'object') {
return unchain(member);
}
return member;
}
});
return proxy;
};
@SparK-Cruz
Copy link
Author

SparK-Cruz commented Sep 27, 2021

const a = {
  doA: () => { console.log('A was done'); },
  doB: () => ({ doD: () => console.log('D was done'), doE: () => 'apple' }),
  doC: () => 'potato'
}

// you can now do:
unchain(a)
  ._.doA()
  ._.doB()
  ._.doC()
  ._.doA()
  .doB()
  ._.doD()
  .doE() // apple

// doB returns an object, which is also enabled to use ._. automatically

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment