Elixir's Enum.group_by in TypeScript

Rosetta Stone: ruby/group_by

How to use

Install via yarn add locutus and import: import { group_by } from 'locutus/elixir/Enum/group_by'.

Or with CommonJS: const { group_by } = require('locutus/elixir/Enum/group_by')

Use a bundler that supports tree-shaking so you only ship the functions you actually use. Vite, webpack, Rollup, and Parcel all handle this. For server-side use this is less of a concern.

Examples

These examples are extracted from test cases that automatically verify our functions against their native counterparts.

#codeexpected result
1group_by(['one', 'two', 'three'], (value) => value.length){3: ['one', 'two'], 5: ['three']}
2group_by([1, 2, 3, 4], (value) => (value % 2 === 0 ? 'even' : 'odd')){odd: [1, 3], even: [2, 4]}
3group_by([1, 2, 3], (value) => (value % 2 === 0 ? 'even' : 'odd'), (value) => value * 10){odd: [10, 30], even: [20]}

Notes

  • Groups values by key selector, similar to Elixir Enum.group_by/3.

Here's what our current TypeScript equivalent to Elixir's Enum.group_by looks like.

type GroupKeySelector<T> = (value: T, index: number, array: T[]) => string | number | symbol
type GroupValueSelector<T, U> = (value: T, index: number, array: T[]) => U

export function group_by<T>(values: T[] | unknown, keySelector: GroupKeySelector<T>): Record<string, T[]>
export function group_by<T, U>(
values: T[] | unknown,
keySelector: GroupKeySelector<T>,
valueSelector: GroupValueSelector<T, U>,
): Record<string, U[]>
export function group_by<T, U>(
values: T[] | unknown,
keySelector: GroupKeySelector<T>,
valueSelector?: GroupValueSelector<T, U>,
): Record<string, unknown[]> {
// discuss at: https://locutus.io/elixir/group_by/
// original by: Kevin van Zonneveld (https://kvz.io)
// note 1: Groups values by key selector, similar to Elixir Enum.group_by/3.
// example 1: group_by(['one', 'two', 'three'], (value) => value.length)
// returns 1: {3: ['one', 'two'], 5: ['three']}
// example 2: group_by([1, 2, 3, 4], (value) => (value % 2 === 0 ? 'even' : 'odd'))
// returns 2: {odd: [1, 3], even: [2, 4]}
// example 3: group_by([1, 2, 3], (value) => (value % 2 === 0 ? 'even' : 'odd'), (value) => value * 10)
// returns 3: {odd: [10, 30], even: [20]}

if (typeof keySelector !== 'function') {
throw new TypeError('group_by(): keySelector must be a function')
}

if (valueSelector !== undefined && typeof valueSelector !== 'function') {
throw new TypeError('group_by(): valueSelector must be a function')
}

if (!Array.isArray(values)) {
return {}
}

const out: Record<string, unknown[]> = {}
for (let i = 0; i < values.length; i++) {
const value = values[i] as T
const key = String(keySelector(value, i, values))
const mapped = valueSelector ? valueSelector(value, i, values) : value
const bucket = out[key] ?? []
bucket.push(mapped)
out[key] = bucket
}

return out
}

Improve this function

Locutus is a community effort following The McDonald's Theory: we ship first iterations, hoping others will improve them. If you see something that could be better, we'd love your contribution.

View on GitHub · Edit on GitHub · View Raw


We have 11 Elixir functions so far - help us add more

Got a rainy Sunday afternoon and a taste for a porting puzzle?

  • Get inspiration from the Elixir documentation.
  • Click "New file" in the appropriate folder on GitHub. This will fork the project to your account, directly add the file to it, and send a Pull Request to us.

We will then review it. If it's useful to the project and in line with our contributing guidelines your work will become part of Locutus and you'll be automatically credited in the authors section accordingly.

« More Elixir Enum functions


Star