The Functions module provides a collection of utility functions for functional programming in TypeScript. It includes common functional programming primitives, function composition utilities, and helper functions for common operations.
Function Evaluation
invoke
This function is a syntax sugar for IIFEs.
Immediately invokes a function and returns its return value.
import { invoke } from 'funkcia/functions';
declare const shape: Shape;
const humanReadableShape = invoke(() => {
switch (shape.kind) {
case 'CIRCLE':
return 'Circle';
case 'SQUARE':
return 'Square';
default:
const invalidKind: never = shape.kind;
throw new Error(`Invalid shape: ${invalidKind}`);
}
});
lazyCompute
Lazily computes a value by invoking a function. The value is computed only once when first accessed.
import { lazyCompute } from 'funkcia/functions';
declare function expensiveComputation(target: object[]): string;
declare const userLogs: object[];
const computation = lazyCompute(() => expensiveComputation(userLogs));
const output = computation.value; // computed only when accessed
const repeatedOutput = computation.value; // cached value returned
This operation is unsafe and can be misleading if misused. Make sure you know what you're doing and use it wisely.
Ideally, you should only use this function when you have a better understanding of your code than TypeScript, which may be unable to narrow down the type of a value.
Returns the provided value coerced to the desired type.
import { coerce, Result } from 'funkcia/functions';
// ┌─── Result<any, SyntaxError>
// â–¼
const result = Result.try(
() => JSON.parse('{ "name": John }'),
error => coerce<SyntaxError>(error) // JSON.parse throws a `SyntaxError`
);
compose
Composes two or more functions into a single function, from left to right.
import { compose } from 'funkcia/functions';
declare function increment(value: number): number;
declare function double(value: number): number;
declare function stringify(value: number): string;
const compute = compose(increment, double, stringify);
const output = compute(9);
// Output: "20"
pipe
Pipes a value through a series of functions, from left to right.
import { pipe } from 'funkcia/functions';
declare function increment(value: number): number;
declare function double(value: number): number;
declare function stringify(value: number): string;
const output = pipe(9, increment, double, stringify);
// Output: "20"