mirror of
https://github.com/idanoo/GoScrobble.git
synced 2024-11-28 03:15:16 +00:00
36 lines
983 B
JavaScript
36 lines
983 B
JavaScript
|
/**
|
||
|
* Safe chained function
|
||
|
*
|
||
|
* Will only create a new function if needed,
|
||
|
* otherwise will pass back existing functions or null.
|
||
|
*
|
||
|
* @param {function} functions to chain
|
||
|
* @returns {function|null}
|
||
|
*/
|
||
|
function createChainedFunction() {
|
||
|
for (var _len = arguments.length, funcs = new Array(_len), _key = 0; _key < _len; _key++) {
|
||
|
funcs[_key] = arguments[_key];
|
||
|
}
|
||
|
|
||
|
return funcs.filter(function (f) {
|
||
|
return f != null;
|
||
|
}).reduce(function (acc, f) {
|
||
|
if (typeof f !== 'function') {
|
||
|
throw new Error('Invalid Argument Type, must only provide functions, undefined, or null.');
|
||
|
}
|
||
|
|
||
|
if (acc === null) return f;
|
||
|
return function chainedFunction() {
|
||
|
for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
|
||
|
args[_key2] = arguments[_key2];
|
||
|
}
|
||
|
|
||
|
// @ts-ignore
|
||
|
acc.apply(this, args); // @ts-ignore
|
||
|
|
||
|
f.apply(this, args);
|
||
|
};
|
||
|
}, null);
|
||
|
}
|
||
|
|
||
|
export default createChainedFunction;
|