⚡ Sangsakala Proxy 🏠 Home
Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 28 additions & 0 deletions Maths/FindMedian.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
/**
* @function findMedian
* @description Finds the median value of an array of numbers.
* The median is the middle value when the array is sorted.
* If the array has an even number of elements, the median is
* the average of the two middle values.
* @param {number[]} arr - An array of numbers
* @returns {number} - The median value
* @see https://en.wikipedia.org/wiki/Median
* @example findMedian([1, 2, 3]) => 2
* @example findMedian([1, 2, 3, 4]) => 2.5
* @example findMedian([5, 3, 1, 4, 2]) => 3
*/
const findMedian = (arr) => {
if (!Array.isArray(arr) || arr.length === 0) {
throw new TypeError('Input must be a non-empty array')
}
if (!arr.every((n) => typeof n === 'number' && !isNaN(n))) {
throw new TypeError('All elements must be numbers')
}
const sorted = [...arr].sort((a, b) => a - b)
const mid = Math.floor(sorted.length / 2)
return sorted.length % 2 !== 0
? sorted[mid]
: (sorted[mid - 1] + sorted[mid]) / 2
}

export { findMedian }
49 changes: 49 additions & 0 deletions Maths/test/FindMedian.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
import { findMedian } from '../FindMedian.js'

describe('findMedian', () => {
test('findMedian([1, 2, 3]) returns 2', () => {
expect(findMedian([1, 2, 3])).toBe(2)
})

test('findMedian([1, 2, 3, 4]) returns 2.5', () => {
expect(findMedian([1, 2, 3, 4])).toBe(2.5)
})

test('findMedian([5, 3, 1, 4, 2]) returns 3', () => {
expect(findMedian([5, 3, 1, 4, 2])).toBe(3)
})

test('findMedian single element returns that element', () => {
expect(findMedian([42])).toBe(42)
})

test('findMedian([1, 1, 1]) returns 1', () => {
expect(findMedian([1, 1, 1])).toBe(1)
})

test('findMedian works with negative numbers', () => {
expect(findMedian([-3, -1, -2])).toBe(-2)
})

test('findMedian works with decimals', () => {
expect(findMedian([1.5, 2.5, 3.5])).toBe(2.5)
})

test('findMedian does not mutate original array', () => {
const arr = [3, 1, 2]
findMedian(arr)
expect(arr).toEqual([3, 1, 2])
})

test('throws TypeError for empty array', () => {
expect(() => findMedian([])).toThrow(TypeError)
})

test('throws TypeError for non-array input', () => {
expect(() => findMedian('123')).toThrow(TypeError)
})

test('throws TypeError for array with non-numbers', () => {
expect(() => findMedian([1, 'two', 3])).toThrow(TypeError)
})
})
Loading