keyBy
Import from @varavel/vdl-plugin-sdk/utils/sets.
Maps each element of a Set based on a provided key-generating function.
This function takes a Set and a function that generates a key from each value. It returns a new Map where the keys are generated by the key function and the values are the corresponding values from the original set. If multiple elements produce the same key, the last value encountered will be used.
Type Parameters
| Type Parameter | Description |
|---|---|
T |
The type of elements in the Set. |
K |
The type of keys to produce in the returned Map. |
Parameters
| Parameter | Type | Description |
|---|---|---|
set |
Set\<T> |
The set of elements to be mapped. |
getKeyFromValue |
(value, value2, set) => K |
A function that generates a key from a value. |
Returns
Map\<K, T>
A Map where the generated keys are mapped to each element's value.
Example
const set = new Set([
{ type: 'fruit', name: 'apple' },
{ type: 'fruit', name: 'banana' },
{ type: 'vegetable', name: 'carrot' }
]);
const result = keyBy(set, item => item.type);
// result will be:
// Map(2) {
// 'fruit' => { type: 'fruit', name: 'banana' },
// 'vegetable' => { type: 'vegetable', name: 'carrot' }
// }