minBy
EditFinds the first item with the smallest finite derived number.
export type MinBySelector<Value> = ( this: void, value: Value, index: number, array: readonly (Value | undefined)[],) => number;
/** Returns the first value with the smallest finite derived number. */export const minBy = <const T>( array: readonly T[], getValue: MinBySelector<T>,): T | undefined => { let result: T | undefined; let minimum = Infinity; let hasResult = false;
for (let index = 0; index < array.length; index += 1) { if (!Object.hasOwn(array, index)) continue; const value = array[index] as T; const candidate = getValue(value, index, array); if (!Number.isFinite(candidate)) continue; if (!hasResult || candidate < minimum) { result = value; minimum = candidate; hasResult = true; } } return result;};Download
Section titled “Download”wget -O src/lib/minBy.ts https://raw.githubusercontent.com/jrTilak/lazykit/HEAD/registry/functions/minBy.tstemp_dir="$(mktemp -d)" && bunx degit jrTilak/lazykit/registry/functions "$temp_dir" && mv "$temp_dir/minBy.ts" src/lib/minBy.ts && rm -r "$temp_dir"Examples
Section titled “Examples”import { minBy } from "./minBy";
const cheapest = minBy( [{ name: "A", price: 20 }, { name: "B", price: 12 }], (item) => item.price);array(readonly T[]) — Candidate values. Empty slots are skipped.getValue((value: T, index, array: readonly (T | undefined)[]) => number) — Produces comparable numbers and is invoked without a receiver.valueis always present; the original array retains skipped holes.- Returns
T | undefined; non-finite results are ignored.