54 lines
1.9 KiB
JavaScript
Raw Permalink Normal View History

2026-05-31 13:21:13 +02:00
import { identity } from "../../function/identity.mjs";
import { range } from "../../math/range.mjs";
import { isArrayLike } from "../predicate/isArrayLike.mjs";
//#region src/compat/array/reduceRight.ts
/**
* Reduces a collection to a single value using an iteratee function, starting from the right.
*
* @param {T[] | ArrayLike<T> | Record<string, T> | null | undefined} collection - The collection to iterate over.
* @param {((accumulator: any, value: any, index: PropertyKey, collection: any) => any) | PropertyKey | object} iteratee - The function invoked per iteration or the key to reduce over.
* @param {any} initialValue - The initial value.
* @returns {any} - Returns the accumulated value.
*
* @example
* // Using a reducer function
* const array = [1, 2, 3];
* reduceRight(array, (acc, value) => acc + value, 0); // => 6
*
* @example
* // Using a reducer function with initialValue
* const array = [1, 2, 3];
* reduceRight(array, (acc, value) => acc + value % 2 === 0, true); // => false
*
* @example
* // Using an object as the collection
* const obj = { a: 1, b: 2, c: 3 };
* reduceRight(obj, (acc, value) => acc + value, 0); // => 6
*/
function reduceRight(collection, iteratee = identity, accumulator) {
if (!collection) return accumulator;
let keys;
let startIndex;
if (isArrayLike(collection)) {
keys = range(0, collection.length).reverse();
if (accumulator == null && collection.length > 0) {
accumulator = collection[collection.length - 1];
startIndex = 1;
} else startIndex = 0;
} else {
keys = Object.keys(collection).reverse();
if (accumulator == null) {
accumulator = collection[keys[0]];
startIndex = 1;
} else startIndex = 0;
}
for (let i = startIndex; i < keys.length; i++) {
const key = keys[i];
const value = collection[key];
accumulator = iteratee(accumulator, value, key, collection);
}
return accumulator;
}
//#endregion
export { reduceRight };