Created
March 23, 2023 23:23
-
-
Save ycmjason/7a7149dcd728a041f8e4c128d4dc009a to your computer and use it in GitHub Desktop.
A beautiful implementation of groupBy 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
export const groupBy = <X, K extends PropertyKey>( | |
getKey: (x: X) => K, | |
xs: readonly X[], | |
): { readonly [k in K]?: readonly (X | undefined)[] } => { | |
const grouped: { [k in K]?: (X | undefined)[] } = {}; | |
for (const x of xs) { | |
const key = getKey(x); | |
grouped[key] ??= []; | |
// we have initialised ^ so grouped[key] won't be undefined | |
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion | |
grouped[key]!.push(x); | |
} | |
return grouped; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment