cond
util
Creates a function that iterates over pairs and invokes the corresponding function of the first predicate to return truthy.
Installation
Import
import { cond } from '@tulx/utils';Source Code
Implementation
/**
* Creates a function that iterates over pairs and invokes the corresponding function of the first predicate to return truthy.
*
* @param pairs - The predicate-function pairs.
* @returns Returns the new composite function.
*
* @example
* ```ts
* const func = cond([
* [matches({ 'user': 'barney' }), () => 'A'],
* [matches({ 'age': 36 }), () => 'B'],
* [stubTrue, () => 'C']
* ]);
* func({ 'user': 'barney', 'active': false }); // 'A'
* func({ 'user': 'fred', 'age': 36 }); // 'B'
* func({ 'user': 'pebbles', 'age': 1 }); // 'C'
* ```
*/
export function cond<T, R>(
pairs: readonly [(value: T) => boolean, (value: T) => R][]
): (value: T) => R | undefined {
return function (value: T): R | undefined {
for (const [predicate, func] of pairs) {
if (predicate(value)) {
return func(value);
}
}
return undefined;
};
}
Example
import { cond } from '@tulx/utils';
const func = cond([
[matches({ 'user': 'barney' }), () => 'A'],
[matches({ 'age': 36 }), () => 'B'],
[stubTrue, () => 'C']
]);
func({ 'user': 'barney', 'active': false }); // 'A'
func({ 'user': 'fred', 'age': 36 }); // 'B'
func({ 'user': 'pebbles', 'age': 1 }); // 'C'Related Functions
attempt
Attempts to invoke func, returning either the result or the caught error object.
bindAll
Binds methods of an object to the object itself, overwriting the existing method.
conforms
Creates a function that invokes the predicate properties of source with the corresponding property values of a given object.
constant
Creates a function that returns value.
defaultTo
Checks value to determine whether a default value should be returned in its place.
flow
Creates a function that returns the result of invoking the given functions with the this binding of the created function.