typedash
Version:
modern, type-safe collection of utility functions
1 lines • 2.26 kB
Source Map (JSON)
{"version":3,"file":"sum-CSt9AUZP.cjs","names":[],"sources":["../src/functions/sum/sum.ts"],"sourcesContent":["import type { 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<readonly 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<readonly 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"],"mappings":";;;;;;;;AAwCA,SAAgB,IACd,OACA,QACQ;AACR,KAAI,SAAS,KACX,QAAO;AAWT,QARgB,MAAM,KAAa,OAAO,OAAO,WAAW;AAK1D,SAHE,SAAS,OAAO,OAAO,OAAO,IAE5B,SAAS;GAEb,CAEa,QAAQ,OAAO,UAAU,QAAQ,OAAO,EAAE"}