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
23 changes: 23 additions & 0 deletions Maths/FindMean.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
/**
* @function findMean
* @description Finds the mean (average) value of an array of numbers.
* The mean is calculated by summing all elements and dividing
* by the total count.
* @param {number[]} arr - An array of numbers
* @returns {number} - The mean value
* @see https://en.wikipedia.org/wiki/Mean
* @example findMean([1, 2, 3]) => 2
* @example findMean([1, 2, 3, 4]) => 2.5
* @example findMean([10, 20, 30]) => 20
*/
const findMean = (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')
}
return arr.reduce((sum, n) => sum + n, 0) / arr.length
}

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

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

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

test('findMean([10, 20, 30]) returns 20', () => {
expect(findMean([10, 20, 30])).toBe(20)
})

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

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

test('findMean works with decimals', () => {
expect(findMean([1.5, 2.5, 3.0])).toBeCloseTo(2.333)
})

test('findMean([0, 0, 0]) returns 0', () => {
expect(findMean([0, 0, 0])).toBe(0)
})

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

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

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

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