Skip to content

Commit 2f6f590

Browse files
feat: add find mode algorithm
1 parent 5c39e87 commit 2f6f590

2 files changed

Lines changed: 73 additions & 0 deletions

File tree

‎Maths/FindMode.js‎

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
/**
2+
* @function findMode
3+
* @description Finds the mode of an array of numbers. The mode is the
4+
* value that appears most frequently. If multiple values appear the
5+
* same number of times, all of them are returned.
6+
* @param {number[]} arr - An array of numbers
7+
* @returns {number[]} - An array containing the mode value(s)
8+
* @see https://en.wikipedia.org/wiki/Mode_(statistics)
9+
* @example findMode([1, 2, 2, 3]) => [2]
10+
* @example findMode([1, 1, 2, 2]) => [1, 2]
11+
* @example findMode([1, 2, 3]) => [1, 2, 3]
12+
*/
13+
const findMode = (arr) => {
14+
if (!Array.isArray(arr) || arr.length === 0) {
15+
throw new TypeError('Input must be a non-empty array')
16+
}
17+
if (!arr.every((n) => typeof n === 'number' && !isNaN(n))) {
18+
throw new TypeError('All elements must be numbers')
19+
}
20+
const frequency = {}
21+
for (const num of arr) {
22+
frequency[num] = (frequency[num] || 0) + 1
23+
}
24+
const maxFreq = Math.max(...Object.values(frequency))
25+
return Object.keys(frequency)
26+
.filter((key) => frequency[key] === maxFreq)
27+
.map(Number)
28+
}
29+
30+
export { findMode }

‎Maths/test/FindMode.test.js‎

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
import { findMode } from '../FindMode.js'
2+
3+
describe('findMode', () => {
4+
test('findMode([1, 2, 2, 3]) returns [2]', () => {
5+
expect(findMode([1, 2, 2, 3])).toEqual([2])
6+
})
7+
8+
test('findMode([1, 1, 2, 2]) returns [1, 2]', () => {
9+
expect(findMode([1, 1, 2, 2])).toEqual([1, 2])
10+
})
11+
12+
test('findMode([1, 2, 3]) returns [1, 2, 3]', () => {
13+
expect(findMode([1, 2, 3])).toEqual([1, 2, 3])
14+
})
15+
16+
test('findMode single element returns that element', () => {
17+
expect(findMode([5])).toEqual([5])
18+
})
19+
20+
test('findMode([3, 3, 3]) returns [3]', () => {
21+
expect(findMode([3, 3, 3])).toEqual([3])
22+
})
23+
24+
test('findMode works with negative numbers', () => {
25+
expect(findMode([-1, -1, 2])).toEqual([-1])
26+
})
27+
28+
test('findMode([1, 2, 2, 3, 3]) returns [2, 3]', () => {
29+
expect(findMode([1, 2, 2, 3, 3])).toEqual([2, 3])
30+
})
31+
32+
test('throws TypeError for empty array', () => {
33+
expect(() => findMode([])).toThrow(TypeError)
34+
})
35+
36+
test('throws TypeError for non-array input', () => {
37+
expect(() => findMode('123')).toThrow(TypeError)
38+
})
39+
40+
test('throws TypeError for array with non-numbers', () => {
41+
expect(() => findMode([1, 'two', 3])).toThrow(TypeError)
42+
})
43+
})

0 commit comments

Comments
 (0)