src/mean.js
zzmq.dev@gmail.com/mathkit / src / mean.js
@ 9271926f
Download
Ladder Summary
- file Provides a `mean` function that calculates the arithmetic average of an array of numbers, returning NaN for empty arrays or any non‑numeric or non‑finite values.
/**
* Computes the arithmetic mean of an array of numbers.
*
* @param {number[]} numbers - Array of numeric values.
* @returns {number} The mean of the numbers, or NaN for empty array or invalid inputs.
*/
export function mean(numbers) {
if (!Array.isArray(numbers) || numbers.length === 0) return NaN;
let sum = 0;
for (const n of numbers) {
if (typeof n !== "number" || !Number.isFinite(n)) return NaN;
sum += n;
}
return sum / numbers.length;
}