Skip to content

reduce

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

function reduce<K, V, A>(
   map, 
   callback, 
   initialValue?): A;

Reduces a Map to a single value by iterating through its entries and applying a callback function.

This function iterates through all entries of the Map and applies the callback function to each entry, 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 Map is empty, a TypeError is thrown.

Type Parameters

Type Parameter Default type Description
K - The type of keys in the Map.
V - The type of values in the Map.
A V -

Parameters

Parameter Type Description
map Map\<K, V> The Map to reduce.
callback (accumulator, value, key, map) => A A function that processes each entry and updates the accumulator.
initialValue? A The initial value for the accumulator. If not provided, the first value in the Map is used.

Returns

A

The final accumulated value.

Throws

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

Examples

const map = new Map([
  ['a', 1],
  ['b', 2],
  ['c', 3]
]);
const result = reduce(map, (acc, value) => acc + value, 0);
// result will be: 6
const map = new Map([
  ['a', 10],
  ['b', 20]
]);
const result = reduce(map, (acc, value) => acc + value);
// result will be: 30 (starts with first value 10)