From 660ac2a05aaecfc7cf54f924134ac1467578a520 Mon Sep 17 00:00:00 2001 From: djalmajr Date: Sun, 16 Apr 2023 18:53:19 -0300 Subject: [PATCH] Added groupBy --- src/groupBy.ts | 20 ++++++++++++++++++++ src/index.ts | 1 + 2 files changed, 21 insertions(+) create mode 100644 src/groupBy.ts diff --git a/src/groupBy.ts b/src/groupBy.ts new file mode 100644 index 0000000..7967c8d --- /dev/null +++ b/src/groupBy.ts @@ -0,0 +1,20 @@ +import { curry } from './curry'; +import { Obj } from './types'; + +interface GroupByFn { + (fn: (a: T) => unknown): (arr: T[]) => Obj; + (fn: (a: T) => unknown, arr: T[]): Obj; +} + +/** + * TODO: adicionar documentaĆ§Ć£o + */ +export const groupBy = curry((fn: Function, items: unknown[]) => { + const res = {} as Obj; + for (const item of items) { + const key = fn(item); + res[key] ||= []; + res[key].push(item); + } + return res; +}) as GroupByFn; diff --git a/src/index.ts b/src/index.ts index 955863d..e07b0fd 100644 --- a/src/index.ts +++ b/src/index.ts @@ -22,6 +22,7 @@ export * from './flow'; export * from './formatCurrency'; export * from './formatPhone'; export * from './get'; +export * from './groupBy'; export * from './groupByEveryN'; export * from './includes'; export * from './isArray';