// 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.
 *
 * @template 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
 * ```ts
 * import { sumOf } from "@std/collections/sum-of";
 * import { assertEquals } from "@std/assert/assert-equals";
 *
 * const people = [
 *   { name: "Anna", age: 34 },
 *   { name: "Kim", age: 42 },
 *   { name: "John", age: 23 },
 * ];
 *
 * const totalAge = sumOf(people, (person) => person.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;
}

// denoCacheMetadata={"headers":{"content-length":"1017","x-jsr-backend":"modules","etag":"\"5b4f69b10d6eabcd59123d6142d758d1\"","x-robots-tag":"noindex","date":"Tue, 28 Jul 2026 12:31:15 GMT","server":"cloudflare","content-type":"text/typescript","content-security-policy":"default-src 'none'; script-src 'none'; style-src 'none'; img-src 'none'; font-src 'none'; connect-src 'none'; frame-src 'none'; object-src 'none'; frame-ancestors 'none'; sandbox; form-action 'none';","set-cookie":"__cf_bm=vBjE.DDMLVzzwXIin07.Sh8Zkx4woK.ag9PlVUwyzAY-1785241874.9654446-1.0.1.1-Xgomn7YdDgatPULGIdVWHMpmN46X2bmwAoBg1LDyqZfJtylGqwYYKEGB6l87X.fUfHUrkIeFDNsi5RZtQNibDNMmAksHAo0rtHHXuFGgN3hwNs4i87hc7qxq5QEWkcyB; HttpOnly; SameSite=None; Secure; Path=/; Domain=jsr.io; Expires=Tue, 28 Jul 2026 13:01:15 GMT","alt-svc":"h3=\":443\"; ma=86400","report-to":"{\"group\":\"cf-nel\",\"max_age\":604800,\"endpoints\":[{\"url\":\"https://a.nel.cloudflare.com/report/v4?s=0xOyVPi58l9nV43w2Zzdyxv%2Be9skWrzXXJxehXvwgNeWmVAU9QJm4ukXHSOkIwhz1JZ8kBoL7zXuuxSoR6Cx6ynXRG3V3nR8zQcP09KL8tD2Eqkes4uws3I%3D\"}]}","nel":"{\"report_to\":\"cf-nel\",\"success_fraction\":0.0,\"max_age\":604800}","x-content-type-options":"nosniff","cache-control":"public, max-age=31536000, immutable","vary":"Origin","access-control-allow-origin":"*","cf-ray":"a223e6564f3c7db6-LAX","access-control-expose-headers":"*","cross-origin-resource-policy":"cross-origin"},"url":"https://jsr.io/@std/collections/0.224.2/sum_of.ts","time":1785241875}