bucketing
Version:
group an array of items into buckets
50 lines (49 loc) • 1.6 kB
TypeScript
/**
* A map in which each key-value pair is a bucket. The key is the key of
* bucket's label, and the value is an array of items that all fall under said
* bucket.
*/
export interface ItemBuckets<Item> {
[key: string]: Item[];
}
/**
* A map that maps from key to label.
*/
export interface LabelMap<Label> {
[key: string]: Label;
}
/**
* The result from running `group` on a list of items.
*/
export interface Grouping<Item, Label> {
/**
* The original `items` given to `group`.
*/
items: Item[];
/**
* A unique array of labels generated from `items`. The key generated by the
* `on` function is used to determine label equality.
*/
labels: Label[];
/**
* A map in which each key-value pair is a bucket. The key is the key of
* bucket's label, and the value is an array of items that all fall under
* said bucket.
*/
keyToItems: ItemBuckets<Item>;
/**
* A map that maps from key to label.
*/
keyToLabel: LabelMap<Label>;
}
/**
* Takes `items`, buckets them using the labels generated from the `by`
* function, and keys those labels using the keys generated from the `on`
* function. The `on` function must generate unique keys for a given label:
* no two labels should share the same key.
*
* @param items The list of items to group
* @param by A function that produces a label given an item
* @param on A function that produces a key given a label
*/
export declare function group<Item, Label>(items: Item[], by: (item: Item) => Label, on: (label: Label) => string): Grouping<Item, Label>;