Skip to content

Commit c6d109c

Browse files
feat: add find mean algorithm
1 parent 5c39e87 commit c6d109c

2 files changed

Lines changed: 72 additions & 0 deletions

File tree

‎Maths/FindMean.js‎

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

‎Maths/test/FindMean.test.js‎

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

0 commit comments

Comments
 (0)