diff --git a/Maths/FindMean.js b/Maths/FindMean.js new file mode 100644 index 0000000000..6133532d9f --- /dev/null +++ b/Maths/FindMean.js @@ -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 } diff --git a/Maths/test/FindMean.test.js b/Maths/test/FindMean.test.js new file mode 100644 index 0000000000..037b875d4a --- /dev/null +++ b/Maths/test/FindMean.test.js @@ -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) + }) +})