merge: Improve Mean method (#874)

This commit is contained in:
YATIN KATHURIA
2021-12-15 22:58:28 +05:30
committed by GitHub
parent bbdb5cf38a
commit 3d2a48f798
2 changed files with 24 additions and 20 deletions

View File

@ -1,29 +1,23 @@
'use strict' /**
/* * @function mean
author: PatOnTheBack * @description This script will find the mean value of a array of numbers.
license: GPL-3.0 or later * @param {Integer[]} nums - Array of integer
* @return {Integer} - mean of nums.
Modified from: * @see [Mean](hhttps://en.wikipedia.org/wiki/Mean)
https://github.com/TheAlgorithms/Python/blob/master/maths/average.py * @example mean([1, 2, 4, 5]) = 3
* @example mean([10, 40, 100, 20]) = 42.5
This script will find the average (mean) of an array of numbers.
More about mean:
https://en.wikipedia.org/wiki/Mean
*/ */
const mean = (nums) => { const mean = (nums) => {
// This is a function returns average/mean of array if (!Array.isArray(nums)) {
let sum = 0 throw new TypeError('Invalid Input')
}
// This loop sums all values in the 'nums' array using forEach loop // This loop sums all values in the 'nums' array using forEach loop
nums.forEach(function (current) { const sum = nums.reduce((sum, cur) => sum + cur, 0)
sum += current
})
// Divide sum by the length of the 'nums' array. // Divide sum by the length of the 'nums' array.
const avg = sum / nums.length return sum / nums.length
return avg
} }
export { mean } export { mean }

View File

@ -4,8 +4,18 @@ describe('Tests for average mean', () => {
it('should be a function', () => { it('should be a function', () => {
expect(typeof mean).toEqual('function') expect(typeof mean).toEqual('function')
}) })
it('should throw error for invalid input', () => {
expect(() => mean(123)).toThrow()
})
it('should return the mean of an array of numbers', () => { it('should return the mean of an array of numbers', () => {
const meanFunction = mean([1, 2, 4, 5]) const meanFunction = mean([1, 2, 4, 5])
expect(meanFunction).toBe(3) expect(meanFunction).toBe(3)
}) })
it('should return the mean of an array of numbers', () => {
const meanFunction = mean([10, 40, 100, 20])
expect(meanFunction).toBe(42.5)
})
}) })