UNPKG

typedash

Version:

modern, type-safe collection of utility functions

1 lines 2.31 kB
{"version":3,"sources":["../../src/functions/sum/sum.ts"],"names":[],"mappings":";AAwCO,SAAS,IACd,OACA,QACQ;AACR,MAAI,SAAS,MAAM;AACjB,WAAO;AAAA,EACT;AAEA,QAAM,UAAU,MAAM,IAAY,CAAC,OAAO,OAAO,WAAW;AAC1D,UAAM,SACJ,SAAS,OAAO,OAAO,MAAM;AAAA,KAE3B,SAAS;AACb,WAAO;AAAA,EACT,CAAC;AAED,SAAO,QAAQ,OAAO,CAAC,OAAO,UAAU,QAAQ,OAAO,CAAC;AAC1D","sourcesContent":["import { Maybe } from '../../types';\n\n/**\n * Computes the sum of all values in array. If array is empty or nil, `0` is returned.\n * `null` or `undefined` values are treated as `0`.\n * @param array The array to iterate over.\n * @returns The sum of all values in the array, or `0` if the array is empty or nil.\n * @example\n * ```ts\n * sum([1, 2, 3]); // 6\n * sum([]); // 0\n * sum(null); // 0\n * sum([1, 2, null, 3, undefined, 4]); // 10\n * ```\n */\nexport function sum(array: Maybe<ReadonlyArray<Maybe<number>>>): number;\n/**\n * Computes the sum of all values in array. If array is empty or nil, `0` is returned.\n * @param array The array to iterate over.\n * @param mapper The function used to extract a numeric value from each element.\n * @returns The sum of all values in the array, or `0` if the array is empty or nil.\n * @example\n * ```ts\n * sum([\n * { value: 1 },\n * { value: 2 },\n * { value: 3 }\n * ], (element) => element.value); // 6\n * ```\n */\nexport function sum<T>(\n array: Maybe<readonly T[]>,\n mapper: ArrayIterator<T>\n): number;\n/**\n * Implementation for all overloads.\n * @param array The array to iterate over.\n * @param mapper The function used to extract a numeric value from each element.\n * @returns The sum of all values in the array, or `0` if the array is empty or nil.\n */\nexport function sum<T>(\n array: Maybe<ReadonlyArray<Maybe<T>>>,\n mapper?: ArrayIterator<Maybe<T>>\n): number {\n if (array == null) {\n return 0;\n }\n\n const numbers = array.map<number>((value, index, array_) => {\n const result =\n mapper?.(value, index, array_) ??\n // if there's no iteratee, we're in the overload of `sum` that only takes an array of numbers\n ((value ?? 0) as number);\n return result;\n });\n\n return numbers.reduce((draft, value) => draft + value, 0);\n}\n\ntype ArrayIterator<T> = (\n value: T,\n index: number,\n array: readonly T[]\n) => number;\n"]}