deno.land / std@0.224.0 / collections / sum_of.ts

sum_of.ts
View Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
// Copyright 2018-2024 the Deno authors. All rights reserved. MIT license.// This module is browser compatible.
/** * Applies the given selector to all elements in the given collection and * calculates the sum of the results. * * @example * ```ts * import { sumOf } from "https://deno.land/std@$STD_VERSION/collections/sum_of.ts"; * import { assertEquals } from "https://deno.land/std@$STD_VERSION/assert/assert_equals.ts"; * * const people = [ * { name: "Anna", age: 34 }, * { name: "Kim", age: 42 }, * { name: "John", age: 23 }, * ]; * const totalAge = sumOf(people, (i) => i.age); * * assertEquals(totalAge, 99); * ``` */export function sumOf<T>( array: Iterable<T>, selector: (el: T) => number,): number { let sum = 0;
for (const i of array) { sum += selector(i); }
return sum;}
std

Version Info

Tagged at
6 months ago