std/collections/sum_of.ts

43 lines
1004 B
TypeScript
Raw Normal View History

// Copyright 2018-2024 the Deno authors. All rights reserved. MIT license.
// This module is browser compatible.
2021-08-09 08:55:26 +00:00
/**
2022-11-25 11:40:23 +00:00
* Applies the given selector to all elements in the given collection and
* calculates the sum of the results.
2021-08-09 08:55:26 +00:00
*
* @typeParam T The type of the array elements.
*
* @param array The array to calculate the sum of.
* @param selector The selector function to get the value to sum.
*
* @returns The sum of all elements in the collection.
*
* @example Basic usage
2021-08-09 08:55:26 +00:00
* ```ts
* import { sumOf } from "@std/collections/sum-of";
* import { assertEquals } from "@std/assert";
2021-08-09 08:55:26 +00:00
*
* const people = [
2022-11-25 11:40:23 +00:00
* { name: "Anna", age: 34 },
* { name: "Kim", age: 42 },
* { name: "John", age: 23 },
* ];
*
* const totalAge = sumOf(people, (person) => person.age);
2021-08-09 08:55:26 +00:00
*
2022-11-25 11:40:23 +00:00
* assertEquals(totalAge, 99);
2021-08-09 08:55:26 +00:00
* ```
*/
export function sumOf<T>(
array: Iterable<T>,
2021-08-09 08:55:26 +00:00
selector: (el: T) => number,
): number {
let sum = 0;
for (const i of array) {
sum += selector(i);
}
return sum;
}