mauss
Version:
practical functions and reusable configurations
39 lines (38 loc) • 1.68 kB
JavaScript
/**
* A type-safe higher-order function that accepts a function with one or more parameters and returns a function that can take in one or more arguments with a max of the parameters length.
* If the total arguments provided has not yet reached the initial function parameters length, it will return a function until all the required parameters are fulfilled.
*
* @returns a curried function to take in the arguments
*/
export function curry(fn, expected = fn.length) {
return (...args) => {
if (args.length === expected)
return fn(...args);
if (args.length > expected)
return fn(...args.slice(0, expected));
return curry((...next) => fn(...[...args, ...next]), expected - args.length);
};
}
/**
* A function that accepts a function and returns the same function with the order of parameters reversed. This can be used in conjunction with `compare` methods to sort the items in ascending values.
*
* @param fn any function with one or more arguments
* @returns a curried function to take in the arguments
*/
export function inverse(fn) {
return (...parameters) => fn(...parameters.reverse());
}
/**
* A type-safe higher-order function that accepts any number of arguments, it returns a function with the parameters of the first function passed and a return type/value of the last function.
*
* @returns a function that takes in the initial type and returns the final type
*/
export function pipe(...functions) {
return (arg) => {
let pipeline = arg;
for (let i = 0; i < functions.length; i++) {
pipeline = functions[i](pipeline);
}
return pipeline;
};
}