prepost
Version:
Alter arguments and return values before and after a function is called
63 lines (47 loc) • 1.84 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = pre;
function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } }
var preCallNoop = function preCallNoop() {
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
return args;
};
// Alter the arguments before they are passed to the function
function pre() {
var _ref;
for (var _len2 = arguments.length, args = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
args[_key2] = arguments[_key2];
}
// Flatten args so that pre functions can be passed as arrays
args = (_ref = []).concat.apply(_ref, _toConsumableArray(args));
if (args.length < 2) {
throw new Error('Two arguments required');
} else if (args.length > 2) {
args = [args[0], pre.apply(undefined, _toConsumableArray(args.slice(1)))];
}
var preFn = args[0] || preCallNoop;
if (typeof preFn !== 'function') {
throw new TypeError('Pre function must be a function');
}
var callFn = args[1];
if (typeof callFn !== 'function') {
throw new TypeError('Function to call must be a function');
}
return function () {
for (var _len3 = arguments.length, args = Array(_len3), _key3 = 0; _key3 < _len3; _key3++) {
args[_key3] = arguments[_key3];
}
args = preFn.apply(undefined, _toConsumableArray(args));
if (Array.isArray(args)) {
return callFn.apply(undefined, _toConsumableArray(args));
}
// Args can be a promise which should be resolved before callFn is called
return args.then(function (args) {
return callFn.apply(undefined, _toConsumableArray(args));
});
};
}