Skip to content

Instantly share code, notes, and snippets.

@SparK-Cruz
Created November 28, 2020 19:45
Show Gist options
  • Save SparK-Cruz/34d96397dd4f1e23e244a51a9f00c2f9 to your computer and use it in GitHub Desktop.
Save SparK-Cruz/34d96397dd4f1e23e244a51a9f00c2f9 to your computer and use it in GitHub Desktop.
Allows you to chain calls for void methods in third party objects
exports.chain = function (subject) {
const proxy = new Proxy(subject, {
get(target, name, receiver) {
const member = Reflect.get(target, name, receiver);
if (typeof member === 'function') {
return function () {
const value = member.apply(subject, arguments);
if (typeof value !== 'undefined')
return value;
return proxy;
};
}
return member;
}
});
return proxy;
};
@SparK-Cruz
Copy link
Author

SparK-Cruz commented Nov 28, 2020

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

// you can now do:
chain(a)
  .doA()
  .doB()
  .doC();

// doA and doB are void, so we can chain, doC doesn't return void/undefined so we end up with the string "potato"

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