mirror of
https://github.com/TheAlgorithms/JavaScript.git
synced 2025-07-05 00:01:37 +08:00
merge: Improve Mean method (#874)
This commit is contained in:
@ -1,29 +1,23 @@
|
||||
'use strict'
|
||||
/*
|
||||
author: PatOnTheBack
|
||||
license: GPL-3.0 or later
|
||||
|
||||
Modified from:
|
||||
https://github.com/TheAlgorithms/Python/blob/master/maths/average.py
|
||||
|
||||
This script will find the average (mean) of an array of numbers.
|
||||
|
||||
More about mean:
|
||||
https://en.wikipedia.org/wiki/Mean
|
||||
*/
|
||||
/**
|
||||
* @function mean
|
||||
* @description This script will find the mean value of a array of numbers.
|
||||
* @param {Integer[]} nums - Array of integer
|
||||
* @return {Integer} - mean of nums.
|
||||
* @see [Mean](hhttps://en.wikipedia.org/wiki/Mean)
|
||||
* @example mean([1, 2, 4, 5]) = 3
|
||||
* @example mean([10, 40, 100, 20]) = 42.5
|
||||
*/
|
||||
|
||||
const mean = (nums) => {
|
||||
// This is a function returns average/mean of array
|
||||
let sum = 0
|
||||
if (!Array.isArray(nums)) {
|
||||
throw new TypeError('Invalid Input')
|
||||
}
|
||||
|
||||
// This loop sums all values in the 'nums' array using forEach loop
|
||||
nums.forEach(function (current) {
|
||||
sum += current
|
||||
})
|
||||
const sum = nums.reduce((sum, cur) => sum + cur, 0)
|
||||
|
||||
// Divide sum by the length of the 'nums' array.
|
||||
const avg = sum / nums.length
|
||||
return avg
|
||||
return sum / nums.length
|
||||
}
|
||||
|
||||
export { mean }
|
||||
|
@ -4,8 +4,18 @@ describe('Tests for average mean', () => {
|
||||
it('should be a 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', () => {
|
||||
const meanFunction = mean([1, 2, 4, 5])
|
||||
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)
|
||||
})
|
||||
})
|
||||
|
Reference in New Issue
Block a user