Skip to content

Commit 3d2a48f

Browse files
merge: Improve Mean method (#874)
1 parent bbdb5cf commit 3d2a48f

File tree

2 files changed

+24
-20
lines changed

2 files changed

+24
-20
lines changed

Maths/AverageMean.js

+14-20
Original file line numberDiff line numberDiff line change
@@ -1,29 +1,23 @@
1-
'use strict'
2-
/*
3-
author: PatOnTheBack
4-
license: GPL-3.0 or later
5-
6-
Modified from:
7-
https://github.com/TheAlgorithms/Python/blob/master/maths/average.py
8-
9-
This script will find the average (mean) of an array of numbers.
10-
11-
More about mean:
12-
https://en.wikipedia.org/wiki/Mean
13-
*/
1+
/**
2+
* @function mean
3+
* @description This script will find the mean value of a array of numbers.
4+
* @param {Integer[]} nums - Array of integer
5+
* @return {Integer} - mean of nums.
6+
* @see [Mean](hhttps://en.wikipedia.org/wiki/Mean)
7+
* @example mean([1, 2, 4, 5]) = 3
8+
* @example mean([10, 40, 100, 20]) = 42.5
9+
*/
1410

1511
const mean = (nums) => {
16-
// This is a function returns average/mean of array
17-
let sum = 0
12+
if (!Array.isArray(nums)) {
13+
throw new TypeError('Invalid Input')
14+
}
1815

1916
// This loop sums all values in the 'nums' array using forEach loop
20-
nums.forEach(function (current) {
21-
sum += current
22-
})
17+
const sum = nums.reduce((sum, cur) => sum + cur, 0)
2318

2419
// Divide sum by the length of the 'nums' array.
25-
const avg = sum / nums.length
26-
return avg
20+
return sum / nums.length
2721
}
2822

2923
export { mean }

Maths/test/AverageMean.test.js

+10
Original file line numberDiff line numberDiff line change
@@ -4,8 +4,18 @@ describe('Tests for average mean', () => {
44
it('should be a function', () => {
55
expect(typeof mean).toEqual('function')
66
})
7+
8+
it('should throw error for invalid input', () => {
9+
expect(() => mean(123)).toThrow()
10+
})
11+
712
it('should return the mean of an array of numbers', () => {
813
const meanFunction = mean([1, 2, 4, 5])
914
expect(meanFunction).toBe(3)
1015
})
16+
17+
it('should return the mean of an array of numbers', () => {
18+
const meanFunction = mean([10, 40, 100, 20])
19+
expect(meanFunction).toBe(42.5)
20+
})
1121
})

0 commit comments

Comments
 (0)