@lou.codes/iterables
Version:
🔁 Iterable and AsyncIterable utils
23 lines (22 loc) • 735 B
JavaScript
import { EMPTY_ARRAY, EMPTY_OBJECT } from "@lou.codes/constants/empty.js";
import { set } from "@lou.codes/utils";
import { reduce } from "./reduce.js";
/**
* Groups values of an iterable in an object based on the output of the
* `grouper` function.
*
* @category Reducers
* @example
* ```typescript
* const groupByType = groupBy((value: number) => number % 2 === 0 ? "even" : "odd");
* groupByType([1, 2, 3, 4, 5]); // { even: [2, 4], odd: [1, 3, 5] }
* ```
* @param grouper Grouper function.
* @returns Object with grouped values.
*/
export const groupBy = grouper =>
reduce(item => {
const group = grouper(item);
return groups =>
set(group)([...(groups[group] ?? EMPTY_ARRAY), item])(groups);
})(EMPTY_OBJECT);