Skip to content

sumBy

Edit

Sums finite numeric values produced by a selector.

sumBy.ts
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;
};
Terminal
wget -O src/lib/sumBy.ts https://raw.githubusercontent.com/jrTilak/lazykit/HEAD/registry/functions/sumBy.ts
sumBy.example.ts
import { sumBy } from "./sumBy";
const total = sumBy(
[{ price: 10 }, { price: 15 }],
(item) => item.price
);
// 25
  • array (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. value is always present; the original array retains skipped holes.
  • Throws when the selector returns a non-finite number or the running total overflows.