Elixir's Enum.frequencies_by in TypeScript

How to use

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

Or with CommonJS: const { frequencies_by } = require('locutus/elixir/Enum/frequencies_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
1frequencies_by(['a', 'aa', 'b'], (value) => value.charAt(0)){a: 2, b: 1}
2frequencies_by([1, 2, 3, 4], (value) => (value % 2 === 0 ? 'even' : 'odd')){odd: 2, even: 2}
3frequencies_by([], (value) => String(value)){}

Notes

  • Counts items by selector key, similar to Elixir Enum.frequencies_by/2.

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

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

export function frequencies_by<T>(values: T[] | unknown, selector: FrequencySelector<T>): Record<string, number> {
// discuss at: https://locutus.io/elixir/frequencies_by/
// original by: Kevin van Zonneveld (https://kvz.io)
// note 1: Counts items by selector key, similar to Elixir Enum.frequencies_by/2.
// example 1: frequencies_by(['a', 'aa', 'b'], (value) => value.charAt(0))
// returns 1: {a: 2, b: 1}
// example 2: frequencies_by([1, 2, 3, 4], (value) => (value % 2 === 0 ? 'even' : 'odd'))
// returns 2: {odd: 2, even: 2}
// example 3: frequencies_by([], (value) => String(value))
// returns 3: {}

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

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

const out: Record<string, number> = {}
for (let i = 0; i < values.length; i++) {
const value = values[i] as T
const key = String(selector(value, i, values))
out[key] = (out[key] ?? 0) + 1
}

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