UNPKG

bucketing

Version:

group an array of items into buckets

33 lines (32 loc) 1.13 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); /** * 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 */ function group(items, by, on) { var labels = []; var keyToItems = {}; var keyToLabel = {}; for (var _i = 0, items_1 = items; _i < items_1.length; _i++) { var item = items_1[_i]; var label = by(item); var key = on(label); if (!(key in keyToLabel)) { keyToLabel[key] = label; labels.push(label); } if (!(key in keyToItems)) { keyToItems[key] = []; } keyToItems[key].push(item); } return { items: items, labels: labels, keyToItems: keyToItems, keyToLabel: keyToLabel }; } exports.group = group;