average
The average utility calculates the arithmetic mean of an array of numbers. It provides a simple, functional way to find the average value in a collection.
Source Code
View Source Code
ts
import { sum } from './sum';
/**
* Calculates the average of an array of numbers.
*
* @example
* ```ts
* const arr = [1, 2, 3, 4, 5];
* average(arr); // 3
* average(arr, (num) => num * 2); // 6
* ```
*
* @param array - The array to average.
* @param callback - (optional) A callback function to map each item to a number.
* @returns The average, or `undefined` if the array is empty or contains non-numeric values.
*/
export function average<T>(array: T[], callback?: (item: T) => number): number | undefined {
if (array.length === 0) return undefined;
try {
const result = sum(array, callback) / array.length;
return Number.isNaN(result) ? undefined : result;
} catch {
return undefined;
}
}Features
- Isomorphic: Works in both Browser and Node.js.
- Robust: Handles empty arrays by returning
NaN. - Type-safe: Properly typed for numeric inputs and results.
API
ts
function average<T>(array: T[], callback?: (item: T) => number): number | undefined;Parameters
array: An array of values to be averaged.callback: Optional. A function to map each item to a number or Date before averaging.
Returns
- The arithmetic mean of the provided numbers or dates.
- Returns
undefinedif the input array is empty.
Examples
Basic Usage
ts
import { average } from '@vielzeug/toolkit';
const data = [10, 20, 30, 40, 50];
const mean = average(data); // 30With Callback Function
ts
import { average } from '@vielzeug/toolkit';
const items = [{ value: 10 }, { value: 20 }, { value: 30 }];
average(items, (item) => item.value); // 20
const numbers = [1, 2, 3, 4, 5];
average(numbers, (num) => num * 2); // 6Averaging Dates
ts
import { average } from '@vielzeug/toolkit';
const dates = [new Date('2024-01-01'), new Date('2024-01-03'), new Date('2024-01-05')];
average(dates); // Date object representing 2024-01-03Handling Empty Data
ts
import { average } from '@vielzeug/toolkit';
const result = average([]); // undefinedImplementation Notes
- Internally leverages the
sumutility to calculate the total before dividing by the array length. - Does not automatically filter out
nullorundefinedvalues; ensure your input array contains only numbers for accurate results. - Throws
TypeErrorif the input is not an array.