UNPKG

diginext-utils

Version:
36 lines 1.19 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.max = max; /** * Finds the maximum value in an array. * If a key is provided, finds the maximum value of that property from each object. * * @template T - The type of elements in the array * @param array - The array to search * @param key - Optional key to find maximum value from objects * @returns The maximum value, or 0 if array is empty * * @example * ```ts * max([3, 1, 4, 1, 5]); // 5 * max([{ value: 5 }, { value: 2 }, { value: 8 }], 'value'); // 8 * max([]); // 0 * ``` */ function max(array, key) { if (!Array.isArray(array) || array.length === 0) { return 0; } if (key !== undefined) { return array.reduce((maxVal, item) => { const value = item[key]; const numValue = typeof value === "number" ? value : -Infinity; return numValue > maxVal ? numValue : maxVal; }, -Infinity); } return array.reduce((maxVal, value) => { const numValue = typeof value === "number" ? value : -Infinity; return numValue > maxVal ? numValue : maxVal; }, -Infinity); } //# sourceMappingURL=max.js.map