VDL Plugin SDK

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 ParameterDefault typeDescription
T-The type of elements in the Set.
ATThe type of the accumulator.

Parameters

ParameterTypeDescription
setSet<T>The Set to reduce.
callback(accumulator, value, value2, set) => AA function that processes each element and updates the accumulator.
initialValue?AThe 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)