wallet-core/node_modules/option-chain/index.js

56 lines
1.1 KiB
JavaScript
Raw Normal View History

2017-05-28 00:38:50 +02:00
'use strict';
2017-08-14 05:01:11 +02:00
module.exports = (options, fn, target) => {
const chainables = options.chainableMethods || {};
const spread = options.spread;
const defaults = Object.assign({}, options.defaults);
2017-05-28 00:38:50 +02:00
function extend(target, getter, ctx) {
2017-08-14 05:01:11 +02:00
for (const key of Object.keys(chainables)) {
2017-05-28 00:38:50 +02:00
Object.defineProperty(target, key, {
enumerable: true,
configurable: true,
2017-08-14 05:01:11 +02:00
get() {
2017-05-28 00:38:50 +02:00
return wrap(getter, chainables[key], ctx || this);
}
});
2017-08-14 05:01:11 +02:00
}
2017-05-28 00:38:50 +02:00
}
function wrap(createOpts, extensionOpts, ctx) {
function wrappedOpts() {
2017-08-14 05:01:11 +02:00
return Object.assign(createOpts(), extensionOpts);
2017-05-28 00:38:50 +02:00
}
function wrappedFn() {
2017-08-14 05:01:11 +02:00
let args = new Array(arguments.length);
for (let i = 0; i < args.length; i++) {
2017-05-28 00:38:50 +02:00
args[i] = arguments[i];
}
2017-08-14 05:01:11 +02:00
2017-05-28 00:38:50 +02:00
if (spread) {
args.unshift(wrappedOpts());
} else {
args = [wrappedOpts(), args];
}
2017-08-14 05:01:11 +02:00
2017-05-28 00:38:50 +02:00
return fn.apply(ctx || this, args);
}
extend(wrappedFn, wrappedOpts, ctx);
return wrappedFn;
}
function copyDefaults() {
2017-08-14 05:01:11 +02:00
return Object.assign({}, defaults);
2017-05-28 00:38:50 +02:00
}
if (target) {
extend(target, copyDefaults);
return target;
}
return wrap(copyDefaults);
};