Composes multiple functions into a higher-order one. Goes right to left.
<T, TResult>(...fs: ((x: T) => T)[]) => (x: T) => Tcompose(x => x * x, x => x + 1)(3);
// ⇒ 16- How to compose functions?
Returns the given constant no matter the input.
<T>(x: T) => () => Tconstant(3)("anything");
// ⇒ 3- How to create a function that always returns the same value despite given arguments?
Always return the given value.
<T>(x: T) => Tidentity(5);
// ⇒ 5identity("test");
// ⇒ "test"- How to use the identity function?
- Where and why is identity function useful?
Memoizes the function result so it is not computed for the same parameters. Uses deep equality.
<TResult>(f: (...xs: unknown[]) => TResult) => (...args: unknown[]) => TResultconst f = x => { console.log(x); return x + 1; };
const memoized = memoize(f);
memoized(5);
memoized(5);
memoized(5);
memoized(3);- How to memoize a function?
Memoizes the function result so it is not computed for the same parameters. Uses shallow equality.
<TResult>(f: (...xs: unknown[]) => TResult) => (...args: unknown[]) => TResultconst f = ({ x }) => { console.log(x); return x + 1; };
const memoized = memoizeShallow(f);
memoized({ x: 5 });
memoized({ x: 5 });
memoized({ x: 5 });
memoized({ x: 3 });- How to memoize a function with shallow equality?
Memoizes the function result so it is not computed for the same parameters. Uses the given equality function.
<T>(equals: (x: T[], y: T[]) => boolean) => <TResult>(f: (...xs: T[]) => TResult) => (...args: T[]) => TResultconst f = ({ x }) => { console.log(x); return x + 1; };
const memoized = memoizeWith((a, b) => a.x === b.x)(f);
memoized({ x: 5 });
memoized({ x: 5 });
memoized({ x: 5 });
memoized({ x: 3 });- How to memoize a function with a custom equality function?
It does exactly nothing.
() => voidnoOp("anything");
// ⇒ undefined- How to create a function that does nothing?
Inverts the given function result.
(f: (...xs: unknown[]) => unknown) => (...args: unknown[]) => booleannot(x > 10)(15);
// ⇒ true- How to invert a boolean function?
Pipes an input through given functions.
<T>(...fs: ((x: T) => T)[]) => (x: T) => Tpipe(x => x * x, x => x + 1)(3);
// ⇒ 10- How to pipe an argument through a function?
Runs the given function only when the condition is met.
(predicate: (...xs: unknown[]) => boolean) => (action: (...xs: unknown[]) => unknown) => (...args: unknown[]) => unknownwhen(x => x > 0)(x => console.log(x))(5);
when(x => x > 0)(x => console.log(x))(-3);- How to run a function only when a condition is satisfied?
Runs the given function only when the condition is exactly true.
(action: (...xs: unknown[]) => unknown) => (...args: unknown[]) => unknownwhenTrue(x => console.log(x))(false);
when(x => x > 0)(x => console.log(x))(true);- How to run a function only if its argument is true?
- How to execute function only if a variable is true?