Skip to content

Commit a29faa1

Browse files
feat: add find median algorithm
1 parent 5c39e87 commit a29faa1

2 files changed

Lines changed: 77 additions & 0 deletions

File tree

‎Maths/FindMedian.js‎

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
/**
2+
* @function findMedian
3+
* @description Finds the median value of an array of numbers.
4+
* The median is the middle value when the array is sorted.
5+
* If the array has an even number of elements, the median is
6+
* the average of the two middle values.
7+
* @param {number[]} arr - An array of numbers
8+
* @returns {number} - The median value
9+
* @see https://en.wikipedia.org/wiki/Median
10+
* @example findMedian([1, 2, 3]) => 2
11+
* @example findMedian([1, 2, 3, 4]) => 2.5
12+
* @example findMedian([5, 3, 1, 4, 2]) => 3
13+
*/
14+
const findMedian = (arr) => {
15+
if (!Array.isArray(arr) || arr.length === 0) {
16+
throw new TypeError('Input must be a non-empty array')
17+
}
18+
if (!arr.every((n) => typeof n === 'number' && !isNaN(n))) {
19+
throw new TypeError('All elements must be numbers')
20+
}
21+
const sorted = [...arr].sort((a, b) => a - b)
22+
const mid = Math.floor(sorted.length / 2)
23+
return sorted.length % 2 !== 0
24+
? sorted[mid]
25+
: (sorted[mid - 1] + sorted[mid]) / 2
26+
}
27+
28+
export { findMedian }

‎Maths/test/FindMedian.test.js‎

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

0 commit comments

Comments
 (0)