UNPKG

diginext-utils

Version:
32 lines 992 B
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.sum = sum; /** * Calculates the sum of all elements in an array. * If a key is provided, sums the values of that property from each object. * * @template T - The type of elements in the array * @param array - The array to sum * @param key - Optional key to sum values from objects * @returns The sum of all values, or 0 if array is empty * * @example * ```ts * sum([1, 2, 3, 4]); // 10 * sum([{ value: 5 }, { value: 10 }], 'value'); // 15 * sum([]); // 0 * ``` */ function sum(array, key) { if (!Array.isArray(array) || array.length === 0) { return 0; } if (key !== undefined) { return array.reduce((acc, item) => { const value = item[key]; return acc + (typeof value === "number" ? value : 0); }, 0); } return array.reduce((acc, value) => acc + (typeof value === "number" ? value : 0), 0); } //# sourceMappingURL=sum.js.map