diff --git a/Maths/calculateMean.ts b/Maths/calculateMean.ts new file mode 100644 index 00000000..e52140cf --- /dev/null +++ b/Maths/calculateMean.ts @@ -0,0 +1,21 @@ +/** + * @function calculateMean + * @description This script will find the mean value of a array of numbers. + * @param {number[]} numbers - Array of numeric values + * @return {number} - mean of input numbers + * @see [Mean](https://en.wikipedia.org/wiki/Mean) + * @example calculateMean([1, 2, 4, 5]) = 3 + * @example calculateMean([10, 40, 100, 20]) = 42.5 + */ + +export const calculateMean = (numbers: number[]): number => { + if (numbers.length < 1) { + throw new TypeError("Invalid Input"); + } + + // This loop sums all values in the 'numbers' array using an array reducer + const sum = numbers.reduce((sum, current) => sum + current, 0); + + // Divide sum by the length of the 'numbers' array. + return sum / numbers.length; +}; diff --git a/Maths/test/calculateMean.test.ts b/Maths/test/calculateMean.test.ts new file mode 100644 index 00000000..5fc5022e --- /dev/null +++ b/Maths/test/calculateMean.test.ts @@ -0,0 +1,31 @@ +import { calculateMean } from "../calculateMean"; + +describe("Tests for AverageMean", () => { + it("should be a function", () => { + expect(typeof calculateMean).toEqual("function"); + }); + + it("should throw error for invalid input", () => { + expect(() => calculateMean([])).toThrow(); + }); + + it("should return the mean of an array of consecutive numbers", () => { + const meanFunction = calculateMean([1, 2, 3, 4]); + expect(meanFunction).toBe(2.5); + }); + + it("should return the mean of an array of numbers", () => { + const meanFunction = calculateMean([10, 40, 100, 20]); + expect(meanFunction).toBe(42.5); + }); + + it("should return the mean of an array of decimal numbers", () => { + const meanFunction = calculateMean([1.3, 12.67, 99.14, 20]); + expect(meanFunction).toBe(33.2775); + }); + + it("should return the mean of an array of numbers, including negatives", () => { + const meanFunction = calculateMean([10, -40, 100, -20]); + expect(meanFunction).toBe(12.5); + }); +});