UNPKG

@monstermann/fn

Version:

A utility library for TypeScript.

26 lines (24 loc) 681 B
import { FnError } from "../function/FnError.js"; import { dfdlT } from "@monstermann/dfdl"; //#region src/array/meanOrThrow.ts /** * `meanOrThrow(array)` * * Returns the mean (average) value from `array`, or throws an error if the array is empty. * * ```ts * meanOrThrow([1, 2, 3]); // 2 * meanOrThrow([]); // throws FnError * ``` * * ```ts * pipe([1, 2, 3], meanOrThrow()); // 2 * pipe([], meanOrThrow()); // throws FnError * ``` */ const meanOrThrow = dfdlT((target) => { if (target.length === 0) throw new FnError("Array.meanOrThrow: Target is empty.", [target]); return target.reduce((acc, val) => acc + val, 0) / target.length; }, 1); //#endregion export { meanOrThrow };