UNPKG

call-chainer

Version:

Combine a regular function and a class so that methods of the class become chainable properties of the function that get called automatically.

35 lines (34 loc) 1.04 kB
/* IMPORT */ /* MAIN */ const chainerBase = (Methods, fn, cloned) => { const methods = new Methods(); const chain = (...args) => fn(methods, ...args); const keys = Object.keys(methods); const props = Object.getOwnPropertyNames(Object.getPrototypeOf(methods)); const names = Array.from(new Set([...keys, ...props])); for (const name of names) { if (name === 'constructor') continue; const value = methods[name]; if (typeof value !== 'function') continue; Object.defineProperty(chain, name, { get: () => { if (cloned) { value.call(methods); return chain; } else { const clone = chainerBase(Methods, fn, true); return clone[name]; } } }); } return chain; }; const chainer = (Methods, fn) => { return chainerBase(Methods, fn, false); }; /* EXPORT */ export default chainer;