@jsoldi/hkt
Version:
Higher kinded types for typescript and a few utility monads.
66 lines • 2.73 kB
JavaScript
function _chain(...fs) {
return fs.reduce((acc, f) => (a) => f(acc(a)), id);
}
/** Chains multiple functions together, passing the result of each function to the next. */
export function chain(...fs) {
return _chain(...fs);
}
function _pipe(a, ...fs) {
return _chain(...fs)(a);
}
/** Pipes a value through multiple functions, passing the result of each function to the next. */
export function pipe(a, ...fs) {
return _pipe(a, ...fs);
}
/** Curries a function with two arguments. */
export const curry = (f) => (a) => (b) => f(a, b);
/** Curries a function with three arguments. */
export const curry3 = (f) => (a) => (b) => (c) => f(a, b, c);
/** Curries a function with four arguments. */
export const curry4 = (f) => (a) => (b) => (c) => (d) => f(a, b, c, d);
/** Curries a function with five arguments. */
export const curry5 = (f) => (a) => (b) => (c) => (d) => (e) => f(a, b, c, d, e);
/** Uncurries a function with two arguments. */
export const uncurry = (f) => (a, b) => f(a)(b);
/** Uncurries a function with three arguments. */
export const uncurry3 = (f) => (a, b, c) => f(a)(b)(c);
/** Uncurries a function with four arguments. */
export const uncurry4 = (f) => (a, b, c, d) => f(a)(b)(c)(d);
/** Uncurries a function with five arguments. */
export const uncurry5 = (f) => (a, b, c, d, e) => f(a)(b)(c)(d)(e);
/** Identity function that returns the input value. */
export const id = (a) => a;
/** Negates the result of a function. */
export const not = (f) => (a) => !f(a);
/** Flips the order of arguments of a curried function. */
export const flip = (f) => (b) => (a) => f(a)(b);
/** Converts a function that takes an array to a variadic function. */
export const spread = (f) => (...a) => f(a);
/** Converts a variadic function to a function that takes an array. */
export const unspread = (f) => (a) => f(...a);
/** Creates a deep cache for memoization. */
const deepCache = () => {
const map = { leaf: undefined, node: new Map() };
return (keys, getValue) => {
let item = map;
let miss = false;
for (const key of keys) {
let child = miss ? undefined : item.node.get(key);
if (child === undefined) {
miss = true;
child = { leaf: undefined, node: new Map() };
item.node.set(key, child);
}
item = child;
}
if (item.leaf === undefined)
item.leaf = { value: getValue() };
return item.leaf.value;
};
};
/** Memoizes a function with zero or more arguments. Arguments must be serializable. */
export const memo = (f) => {
const cache = deepCache();
return (...a) => cache(a, () => f(...a));
};
//# sourceMappingURL=utils.js.map