Last active
March 4, 2020 23:17
-
-
Save VitorLuizC/2baa4e96f42e6436c1f622d537ee2ffa to your computer and use it in GitHub Desktop.
A groupBy function in TypeScript.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| function groupBy(fn) { | |
| return function(items) { | |
| return items.reduce(function(groups, item) { | |
| var key = fn(item); | |
| if (!(key in groups)) | |
| // eslint-disable-next-line no-param-reassign | |
| groups[key] = []; | |
| groups[key].push(item); | |
| return groups; | |
| }, Object.create(null)); | |
| }; | |
| } | |
| export default groupBy; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| const groupBy = <T, K extends string>(fn: (item: T) => K) => (items: T[]) => | |
| items.reduce((groups, item) => { | |
| const key = fn(item); | |
| return { | |
| ...groups, | |
| [key]: [...(groups?.[key] ?? []), item] | |
| }; | |
| }, {} as Record<K, T[]>); | |
| export default groupBy; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment