Python's statistics.mode in TypeScript

✓ Verified: Python 3.12
Examples tested against actual runtime. CI re-verifies continuously. Only documented examples are tested.

How to use

Install via yarn add locutus and import: import { mode } from 'locutus/python/statistics/mode'.

Or with CommonJS: const { mode } = require('locutus/python/statistics/mode')

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
1mode([1, 1, 2, 2, 3])1
2mode(['red', 'blue', 'red', 'green'])'red'
3mode([true, false, true])true

Notes

  • Returns the first encountered most-common value.

Here's what our current TypeScript equivalent to Python's statistics.mode looks like.

export function mode<T>(data: T[] | unknown): T {
// discuss at: https://locutus.io/python/statistics/mode/
// parity verified: Python 3.12
// original by: Kevin van Zonneveld (https://kvz.io)
// note 1: Returns the first encountered most-common value.
// example 1: mode([1, 1, 2, 2, 3])
// returns 1: 1
// example 2: mode(['red', 'blue', 'red', 'green'])
// returns 2: 'red'
// example 3: mode([true, false, true])
// returns 3: true

const values = assertStatisticsArray(data, 'mode') as T[]
if (values.length === 0) {
throw new Error('no mode for empty data')
}

let bestValue = values[0] as T
let bestCount = 0
const counts = new Map<T, number>()

for (const value of values) {
const count = (counts.get(value) ?? 0) + 1
counts.set(value, count)
if (count > bestCount) {
bestCount = count
bestValue = value
}
}

return bestValue
}

function assertStatisticsArray(data: unknown, functionName: string): unknown[] {
if (!Array.isArray(data)) {
throw new TypeError(`${functionName}() data must be an array`)
}

return data
}

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


Help us add more

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

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 Python statistics functions


Star