diff --git a/Maths/CalculateMedian.ts b/Maths/CalculateMedian.ts new file mode 100644 index 00000000..1a350cac --- /dev/null +++ b/Maths/CalculateMedian.ts @@ -0,0 +1,27 @@ +/** + * @function calculateMedian + * @description This script will find the meadian value of a array of numbers. + * @param {number[]} numbers - Sorted array of numeric values + * @return {number} - median of input numbers + * @see [Median](https://en.wikipedia.org/wiki/Median) + * @example calculateMedian([1, 2, 4, 5, 8]) = 4 + * @example calculateMedian([1, 2, 4, 5]) = 3 + */ + + +export const calculateMedian = (numbers: number[]): number => { + if (numbers.length < 1) { + throw new TypeError("Invalid Input"); + } + + const totalNumbers = numbers.length; + + if (totalNumbers % 2 === 0){ + let index = (totalNumbers) / 2; + return (sortedArray[index - 1] + sortedArray[index]) / 2; + } else { + let index = (totalNumbers + 1) / 2; + return sortedArray[index - 1]; + } + +}; diff --git a/Maths/test/CalculateMedian.test.ts b/Maths/test/CalculateMedian.test.ts new file mode 100644 index 00000000..57c42f7e --- /dev/null +++ b/Maths/test/CalculateMedian.test.ts @@ -0,0 +1,22 @@ +import { calculateMedian } from "../CalculateMedian"; + +describe("Tests for CalculateMedian", () => { + it("should be a function", () => { + expect(typeof calculateMedian).toEqual("function"); + }); + + it("should throw error for invalid input", () => { + expect(() => calculateMedian([])).toThrow(); + }); + + it("should return the median of an array of numbers - even length", () => { + const medianFunction = calculateMedian([1, 2, 3, 4]); + expect(medianFunction).toBe(2.5); + }); + + it("should return the median of an array of numbers - odd length", () => { + const medianFunction = calculateMedian([1, 2, 3, 4, 6, 8, 9]); + expect(medianFunction).toBe(4); + }); + +});