Skip to content

Commit 1d655b4

Browse files
algorithm: average/mean (#30)
1 parent 66892d7 commit 1d655b4

File tree

2 files changed

+52
-0
lines changed

2 files changed

+52
-0
lines changed

Maths/calculateMean.ts

+21
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
/**
2+
* @function calculateMean
3+
* @description This script will find the mean value of a array of numbers.
4+
* @param {number[]} numbers - Array of numeric values
5+
* @return {number} - mean of input numbers
6+
* @see [Mean](https://en.wikipedia.org/wiki/Mean)
7+
* @example calculateMean([1, 2, 4, 5]) = 3
8+
* @example calculateMean([10, 40, 100, 20]) = 42.5
9+
*/
10+
11+
export const calculateMean = (numbers: number[]): number => {
12+
if (numbers.length < 1) {
13+
throw new TypeError("Invalid Input");
14+
}
15+
16+
// This loop sums all values in the 'numbers' array using an array reducer
17+
const sum = numbers.reduce((sum, current) => sum + current, 0);
18+
19+
// Divide sum by the length of the 'numbers' array.
20+
return sum / numbers.length;
21+
};

Maths/test/calculateMean.test.ts

+31
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
import { calculateMean } from "../calculateMean";
2+
3+
describe("Tests for AverageMean", () => {
4+
it("should be a function", () => {
5+
expect(typeof calculateMean).toEqual("function");
6+
});
7+
8+
it("should throw error for invalid input", () => {
9+
expect(() => calculateMean([])).toThrow();
10+
});
11+
12+
it("should return the mean of an array of consecutive numbers", () => {
13+
const meanFunction = calculateMean([1, 2, 3, 4]);
14+
expect(meanFunction).toBe(2.5);
15+
});
16+
17+
it("should return the mean of an array of numbers", () => {
18+
const meanFunction = calculateMean([10, 40, 100, 20]);
19+
expect(meanFunction).toBe(42.5);
20+
});
21+
22+
it("should return the mean of an array of decimal numbers", () => {
23+
const meanFunction = calculateMean([1.3, 12.67, 99.14, 20]);
24+
expect(meanFunction).toBe(33.2775);
25+
});
26+
27+
it("should return the mean of an array of numbers, including negatives", () => {
28+
const meanFunction = calculateMean([10, -40, 100, -20]);
29+
expect(meanFunction).toBe(12.5);
30+
});
31+
});

0 commit comments

Comments
 (0)