Skip to content

Instantly share code, notes, and snippets.

@ycmjason
Created March 23, 2023 23:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ycmjason/7a7149dcd728a041f8e4c128d4dc009a to your computer and use it in GitHub Desktop.
Save ycmjason/7a7149dcd728a041f8e4c128d4dc009a to your computer and use it in GitHub Desktop.
A beautiful implementation of groupBy in typescript
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