Skip to content

countBy

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

function countBy<T, K>(set, mapper): Map<K, number>;

Counts the occurrences of items in a Set based on a transformation function.

This function takes a Set and a function that generates a key from each value. It returns a Map with the generated keys and their counts as values. The count is incremented for each element for which the transformation produces the same key.

Type Parameters

Type Parameter Description
T The type of elements in the Set.
K The type of keys produced by the transformation function.

Parameters

Parameter Type Description
set Set\<T> The Set to count occurrences from.
mapper (value, value2, set) => K The function to produce a key for counting.

Returns

Map\<K, number>

A Map containing the mapped keys and their counts.

Examples

const set = new Set([1, 2, 3, 4, 5]);
const result = countBy(set, (value) => value % 2 === 0 ? 'even' : 'odd');
// result will be Map(2) { 'odd' => 3, 'even' => 2 }
const set = new Set(['apple', 'banana', 'cherry']);
const result = countBy(set, (value) => value.length);
// result will be Map(2) { 5 => 1, 6 => 2 }