sumBy
EditSums finite numeric values produced by a selector.
export type SumBySelector<Value> = ( this: void, value: Value, index: number, array: readonly (Value | undefined)[],) => number;
/** Sums finite numbers produced by a selector. */export const sumBy = <const T>( array: readonly T[], getValue: SumBySelector<T>,): number => { let sum = 0; 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)) { throw new RangeError("selector must return finite numbers"); } const nextSum = sum + candidate; if (!Number.isFinite(nextSum)) { throw new RangeError("sum must remain finite"); } sum = nextSum; } return sum;};Download
Section titled “Download”wget -O src/lib/sumBy.ts https://raw.githubusercontent.com/jrTilak/lazykit/HEAD/registry/functions/sumBy.tstemp_dir="$(mktemp -d)" && bunx degit jrTilak/lazykit/registry/functions "$temp_dir" && mv "$temp_dir/sumBy.ts" src/lib/sumBy.ts && rm -r "$temp_dir"Examples
Section titled “Examples”import { sumBy } from "./sumBy";
const total = sumBy( [{ price: 10 }, { price: 15 }], (item) => item.price);// 25array(readonly T[]) — Values to total. Empty slots are skipped.getValue((value: T, index, array: readonly (T | undefined)[]) => number) — Produces each amount and is invoked without a receiver.valueis always present; the original array retains skipped holes.- Throws when the selector returns a non-finite number or the running total overflows.