Skip to content

feat: add calculate median #73

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from 1 commit
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
30 changes: 30 additions & 0 deletions Maths/CalculateMedian.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import { IsEven } from "./IsEven";

/**
* @function calculateMedian
* @description This script will find the meadian value of a array of numbers.
* @param {number[]} numbers - 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");
}

let sortedArray: number[] = numbers.sort((n1,n2) => n1 - n2);
const totalNumbers = sortedArray.length;

if (IsEven(totalNumbers)){
let index = (totalNumbers) / 2;
return (sortedArray[index - 1] + sortedArray[index]) / 2;
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
return (sortedArray[index - 1] + sortedArray[index]) / 2;
return (numbers[index - 1] + numbers[index]) / 2;

The array name is numbers which is what I think you meant to use.

} else {
let index = (totalNumbers + 1) / 2;
return sortedArray[index - 1];
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
return sortedArray[index - 1];
return numbers[index - 1];

}

};
22 changes: 22 additions & 0 deletions Maths/test/CalculateMedian.test.ts
Original file line number Diff line number Diff line change
@@ -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);
});

});