Skip to content
VersionSize

sum

Calculates the sum of an array of numbers.

Implementation

View Source Code
ts
/**
 * Sum numbers in an array or numbers mapped by a callback function.
 *
 * @example
 * ```ts
 * sum([1, 2, 3]) // 6
 * sum([{value: 1}, {value: 2}, {value: 3}], (item) => item.value) // 6
 * sum(['apple', 'banana', 'cherry']) // TypeError
 * ```
 *
 * @param array - The array to sum.
 * @param callback - An optional callback function to map the values.
 *
 * @returns The sum of the numbers in the array or the sum of the mapped values.
 */
export function sum<T>(array: T[], callback?: (item: T) => number): number | undefined {
  if (array.length === 0) return undefined;

  return array.reduce<number>((acc, item) => {
    const val = callback ? callback(item) : item;
    if (typeof val !== 'number') {
      throw new TypeError(`Expected number, got ${typeof val}`);
    }
    if (Number.isNaN(val)) {
      throw new TypeError('Cannot sum NaN values');
    }
    return acc + val;
  }, 0);
}

API

ts
function sum<T>(array: T[], callback?: (item: T) => number): number | undefined;

Parameters

  • array: Array of numbers or objects
  • callback: Optional function to extract numeric values from objects

Returns

  • Sum of all numbers, or undefined if array is empty

Examples

Basic Usage

ts
import { sum } from '@vielzeug/toolkit';

sum([1, 2, 3, 4, 5]); // 15
sum([]); // undefined
sum([10, 20, 30]); // 60

With Callback Function

ts
import { sum } from '@vielzeug/toolkit';

const items = [{ price: 10 }, { price: 20 }, { price: 30 }];
sum(items, (item) => item.price); // 60

const orders = [
  { total: 100, tax: 10 },
  { total: 200, tax: 20 },
];
sum(orders, (order) => order.total + order.tax); // 330

Implementation Notes

  • Returns undefined for an empty array
  • Throws TypeError if a non-numeric value is encountered
  • Use callback function to sum specific properties of objects

See Also

  • average: Calculate the average of numbers
  • boil: Reduce array with custom comparator
  • reduce: General array reduction