// Copyright 2018-2024 the Deno authors. All rights reserved. MIT license.
// This module is browser compatible.

/**
 * Calls the given reducer on each element of the given collection, passing its
 * result as the accumulator to the next respective call, starting with the
 * given initialValue. Returns all intermediate accumulator results.
 *
 * @template T The type of the elements in the array.
 * @template O The type of the accumulator.
 *
 * @param array The array to reduce.
 * @param reducer The reducer function to apply to each element.
 * @param initialValue The initial value of the accumulator.
 *
 * @returns An array of all intermediate accumulator results.
 *
 * @example Basic usage
 * ```ts
 * import { runningReduce } from "@std/collections/running-reduce";
 * import { assertEquals } from "@std/assert/assert-equals";
 *
 * const numbers = [1, 2, 3, 4, 5];
 * const sumSteps = runningReduce(numbers, (sum, current) => sum + current, 0);
 *
 * assertEquals(sumSteps, [1, 3, 6, 10, 15]);
 * ```
 */
export function runningReduce<T, O>(
  array: readonly T[],
  reducer: (accumulator: O, current: T, currentIndex: number) => O,
  initialValue: O,
): O[] {
  let currentResult = initialValue;
  return array.map((el, currentIndex) =>
    currentResult = reducer(currentResult, el, currentIndex)
  );
}

// denoCacheMetadata={"headers":{"access-control-expose-headers":"*","cross-origin-resource-policy":"cross-origin","alt-svc":"h3=\":443\"; ma=86400","etag":"\"4b27cff39af64eae76d57472ba106410\"","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';","date":"Tue, 28 Jul 2026 12:31:15 GMT","server":"cloudflare","set-cookie":"__cf_bm=.BhOBcX1nQzAhFfr97ZCgTRl3sdOyWYifNCu.gJsYks-1785241874.9638836-1.0.1.1-tWRPEES.boChY28iSfegKMG0AfrlMmixHlWvTClvKKPxjLe19VnSCXzqBMw8UjvHvqplgAcvU0VnMpekAiSgqm53rs0ZwmBU88G0zL6bKCe42ULThQBNxuhNPp2HDeIv; HttpOnly; SameSite=None; Secure; Path=/; Domain=jsr.io; Expires=Tue, 28 Jul 2026 13:01:15 GMT","content-type":"text/typescript","content-length":"1320","cache-control":"public, max-age=31536000, immutable","vary":"Origin","x-jsr-backend":"modules","x-robots-tag":"noindex","nel":"{\"report_to\":\"cf-nel\",\"success_fraction\":0.0,\"max_age\":604800}","access-control-allow-origin":"*","x-content-type-options":"nosniff","cf-ray":"a223e6564f337db6-LAX","report-to":"{\"group\":\"cf-nel\",\"max_age\":604800,\"endpoints\":[{\"url\":\"https://a.nel.cloudflare.com/report/v4?s=lTZEza3X8PdTrVItnFDJuRtrQRJ0RHwBEDsUVrMvKBvE4O4illYruOrrtXgwszekI%2Bc%2FF1N471PfdYx8mRPPQ8WsbNZAC8t23ccqTprlBvC%2F%2FDtYJE%2BE4Cc%3D\"}]}"},"url":"https://jsr.io/@std/collections/0.224.2/running_reduce.ts","time":1785241875}