Skip to content

reduce

Import from @varavel/vdl-plugin-sdk/utils/sets.

function reduce<T, A>(
   set, 
   callback, 
   initialValue?): A;

Reduces a Set to a single value by iterating through its elements and applying a callback function.

This function iterates through all elements of the Set and applies the callback function to each element, accumulating the result. If an initial value is provided, it is used as the starting accumulator value. If no initial value is provided and the Set is empty, a TypeError is thrown.

Type Parameters

Type Parameter Default type Description
T - The type of elements in the Set.
A T The type of the accumulator.

Parameters

Parameter Type Description
set Set\<T> The Set to reduce.
callback (accumulator, value, value2, set) => A A function that processes each element and updates the accumulator.
initialValue? A The initial value for the accumulator. If not provided, the first element in the Set is used.

Returns

A

The final accumulated value.

Throws

If the Set is empty and no initial value is provided.

Examples

const set = new Set([1, 2, 3]);
const result = reduce(set, (acc, value) => acc + value, 0);
// result will be: 6
const set = new Set([10, 20]);
const result = reduce(set, (acc, value) => acc + value);
// result will be: 30 (starts with first value 10)