fix: improve mean function with input validation and extended tests (#1785)

This commit is contained in:
Fatih BARAÇKILIÇ
2025-09-04 07:01:22 +03:00
committed by GitHub
parent 3f52add84d
commit 19ecb18f0a
2 changed files with 63 additions and 6 deletions

View File

@@ -1,19 +1,30 @@
/**
* @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.
* @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.
* @see [Mean](https://en.wikipedia.org/wiki/Mean)
* @example mean([1, 2, 4, 5]) = 3
* @example mean([10, 40, 100, 20]) = 42.5
*/
const mean = (nums) => {
if (!Array.isArray(nums)) {
const mean = (numbers) => {
if (!Array.isArray(numbers)) {
throw new TypeError('Invalid Input')
} else if (numbers.length === 0) {
throw new Error('Array is empty')
}
return nums.reduce((sum, cur) => sum + cur, 0) / nums.length
let total = 0
numbers.forEach((num) => {
if (typeof num !== 'number') {
throw new TypeError('Invalid Input')
}
total += num
})
return total / numbers.length
}
export { mean }

View File

@@ -18,4 +18,50 @@ describe('Tests for average mean', () => {
const meanFunction = mean([10, 40, 100, 20])
expect(meanFunction).toBe(42.5)
})
it('should return the number itself for a single-element array', () => {
const result = mean([5])
expect(result).toBe(5)
})
it('should throw error for empty array', () => {
expect(() => mean([])).toThrow()
})
it('should throw error for an array containing null', () => {
expect(() => mean([1, 2, null])).toThrow()
})
it('should throw error for an array containing booleans', () => {
expect(() => mean([1, 2, true])).toThrow()
})
it('should throw error for an array containing strings', () => {
expect(() => mean([1, 2, 'asd'])).toThrow()
})
it('should return the mean of an array with negative numbers', () => {
const result = mean([-1, -2, -3, -4])
expect(result).toBe(-2.5)
})
it('should return the mean of an array with floating-point numbers', () => {
const result = mean([1.5, 2.5, 3.5])
expect(result).toBe(2.5)
})
it('should return 0 for an array with zeros', () => {
const result = mean([0, 0, 0])
expect(result).toBe(0)
})
it('should handle very large numbers correctly', () => {
const result = mean([1000000000, 2000000000, 3000000000])
expect(result).toBe(2000000000)
})
it('should return correct mean for an array with integers and floating-point numbers', () => {
const result = mean([1, 2.5, 3])
expect(result).toBeCloseTo(2.1667, 4)
})
})