reduce-first
Version:
Return early from reduce
15 lines (14 loc) • 516 B
TypeScript
/**
* Reduce an array to a single value, but stop at the first non-undefined value.
*
* Like `Array.prototype.find`, but allows for mapping the found value to some new value.
* @example
* ```ts
* const list = ["a", "b", "c", "d", "e"];
* const result = reduceFirst(list, (value) => {
* return value === "c" ? `found ${value}` : undefined;
* });
* // result === "found c"
* ```
*/
export default function reduceFirst<T, U>(array: T[], fn: (currentValue: T, index: number, arr: T[]) => U): U | undefined;