Skip to content

Commit ea783b9

Browse files
zFl4wlesssyedjafer
and
syedjafer
authored
feat(maths): finishes calculate median (#114)
* feat: add calculate median * Resolving comments * feat: improvements & resolves requested changes --------- Co-authored-by: syedjafer <[email protected]>
1 parent 4a60b9a commit ea783b9

File tree

2 files changed

+48
-0
lines changed

2 files changed

+48
-0
lines changed

Maths/CalculateMedian.ts

+25
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
/**
2+
* @function calculateMedian
3+
* @description This function will find the median value of an array of numbers.
4+
* @param {number[]} numbers Sorted array of numeric values.
5+
* @return {number} The median of input numbers.
6+
* @see https://en.wikipedia.org/wiki/Median
7+
* @example calculateMedian([1, 2, 4, 5, 8]) = 4
8+
* @example calculateMedian([1, 2, 4, 5]) = 3
9+
*/
10+
11+
export const calculateMedian = (numbers: number[]): number => {
12+
if (numbers.length < 1) {
13+
throw new TypeError("Input array must contain at least one number.");
14+
}
15+
16+
const totalNumbers = numbers.length;
17+
18+
if (totalNumbers % 2 === 0) {
19+
let index = totalNumbers / 2;
20+
return (numbers[index - 1] + numbers[index]) / 2;
21+
} else {
22+
let index = (totalNumbers + 1) / 2;
23+
return numbers[index - 1];
24+
}
25+
};

Maths/test/CalculateMedian.test.ts

+23
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
import { calculateMedian } from "../CalculateMedian";
2+
3+
describe("Tests for CalculateMedian", () => {
4+
it("should be a function", () => {
5+
expect(typeof calculateMedian).toEqual("function");
6+
});
7+
8+
it("should throw error for invalid input", () => {
9+
expect(() => calculateMedian([])).toThrowError(
10+
"Input array must contain at least one number."
11+
);
12+
});
13+
14+
it("should return the median of an array of numbers - even length", () => {
15+
const medianFunction = calculateMedian([1, 2, 3, 4]);
16+
expect(medianFunction).toBe(2.5);
17+
});
18+
19+
it("should return the median of an array of numbers - odd length", () => {
20+
const medianFunction = calculateMedian([1, 2, 3, 4, 6, 8, 9]);
21+
expect(medianFunction).toBe(4);
22+
});
23+
});

0 commit comments

Comments
 (0)