2021-12-15 22:58:28 +05:30
|
|
|
/**
|
|
|
|
|
* @function mean
|
|
|
|
|
* @description This script will find the mean value of a array of numbers.
|
2025-09-04 07:01:22 +03:00
|
|
|
* @param {number[]} numbers - Array of integer
|
|
|
|
|
* @return {number} - mean of numbers.
|
|
|
|
|
* @throws {TypeError} If the input is not an array or contains non-number elements.
|
|
|
|
|
* @throws {Error} If the input array is empty.
|
2022-02-21 06:58:40 -04:00
|
|
|
* @see [Mean](https://en.wikipedia.org/wiki/Mean)
|
2021-12-15 22:58:28 +05:30
|
|
|
* @example mean([1, 2, 4, 5]) = 3
|
|
|
|
|
* @example mean([10, 40, 100, 20]) = 42.5
|
|
|
|
|
*/
|
2025-09-04 07:01:22 +03:00
|
|
|
const mean = (numbers) => {
|
|
|
|
|
if (!Array.isArray(numbers)) {
|
2021-12-15 22:58:28 +05:30
|
|
|
throw new TypeError('Invalid Input')
|
2025-09-04 07:01:22 +03:00
|
|
|
} else if (numbers.length === 0) {
|
|
|
|
|
throw new Error('Array is empty')
|
2021-12-15 22:58:28 +05:30
|
|
|
}
|
2019-07-01 15:07:01 -04:00
|
|
|
|
2025-09-04 07:01:22 +03:00
|
|
|
let total = 0
|
|
|
|
|
numbers.forEach((num) => {
|
|
|
|
|
if (typeof num !== 'number') {
|
|
|
|
|
throw new TypeError('Invalid Input')
|
|
|
|
|
}
|
|
|
|
|
total += num
|
|
|
|
|
})
|
|
|
|
|
|
|
|
|
|
return total / numbers.length
|
2019-07-01 15:07:01 -04:00
|
|
|
}
|
|
|
|
|
|
2020-10-11 19:47:49 +00:00
|
|
|
export { mean }
|