avocado-old/packages/core/function.js
2019-11-11 15:29:37 -06:00

44 lines
1.2 KiB
JavaScript

/**
* Composes single-argument functions from right to left. The rightmost
* function can take multiple arguments as it provides the signature for
* the resulting composite function.
*
* @param {...Function} funcs The functions to compose.
* @returns {Function} A function obtained by composing the argument functions
* from right to left. For example, compose(f, g, h) is identical to doing
* (...args) => f(g(h(...args))).
*/
export function compose(...funcs) {
if (funcs.length === 0) {
return arg => arg;
}
if (funcs.length === 1) {
return funcs[0];
}
return funcs.reduce((a, b) => (...args) => a(b(...args)));
}
export function fastApply(holder, fn, args) {
if (holder || args.length > 5) {
return fn.apply(holder, args);
}
if (0 === args.length) {
return fn();
}
if (1 === args.length) {
return fn(args[0]);
}
if (2 === args.length) {
return fn(args[0], args[1]);
}
if (3 === args.length) {
return fn(args[0], args[1], args[2]);
}
if (4 === args.length) {
return fn(args[0], args[1], args[2], args[3]);
}
if (5 === args.length) {
return fn(args[0], args[1], args[2], args[3], args[4]);
}
}