reduceRight
collection
This method is like reduce except that it iterates over elements of collection from right to left.
Installation
Import
import { reduceRight } from '@tulx/utils';Source Code
Implementation
/**
* This method is like reduce except that it iterates over elements of collection from right to left.
*
* @param collection - The collection to iterate over.
* @param iteratee - The function invoked per iteration.
* @param accumulator - The initial value.
* @returns Returns the accumulated value.
*
* @example
* ```ts
* const array = [[0, 1], [2, 3], [4, 5]];
* reduceRight(array, (flattened, other) => flattened.concat(other), []); // [4, 5, 2, 3, 0, 1]
* ```
*/
export function reduceRight<T, TResult>(
collection: readonly T[] | Record<string, T>,
iteratee: (
accumulator: TResult,
value: T,
index: number | string,
collection: readonly T[] | Record<string, T>
) => TResult,
accumulator: TResult
): TResult {
if (Array.isArray(collection)) {
for (let i = collection.length - 1; i >= 0; i--) {
accumulator = iteratee(accumulator, collection[i], i, collection);
}
} else {
const record = collection as Record<string, T>;
const keys = Object.keys(record).reverse();
for (const key of keys) {
accumulator = iteratee(accumulator, record[key], key, record);
}
}
return accumulator;
}
Example
import { reduceRight } from '@tulx/utils';
const array = [[0, 1], [2, 3], [4, 5]];
reduceRight(array, (flattened, other) => flattened.concat(other), []); // [4, 5, 2, 3, 0, 1]Related Functions
countBy
Creates an object composed of keys generated from the results of running each element of collection thru iteratee. The corresponding value of each key is the number of times the key was returned by iteratee.
each
Iterates over elements of collection and invokes iteratee for each element. The iteratee is invoked with three arguments: (value, index|key, collection).
eachRight
This method is like each except that it iterates over elements of collection from right to left.
every
Checks if predicate returns truthy for all elements of collection.
filter
Iterates over elements of collection, returning an array of all elements predicate returns truthy for.
find
Iterates over elements of collection, returning the first element predicate returns truthy for.