Skip to content
VersionSize

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.

Implementation

View Source Code
ts
import { sum } from './sum';

/**
 * Calculates the average of an array of numbers or dates.
 *
 * @example
 * ```ts
 * const arr = [1, 2, 3, 4, 5];
 * average(arr); // 3
 * average(arr, (num) => num * 2); // 6
 * average(arr, (num) => new Date(Date.now() + 1000 * 60 * 60 * 24 * num); // Date object representing 3 days from now
 * ```
 *
 * @param array - The array of numbers or dates to average.
 * @param callback - (optional) A callback function to map the values.
 * @returns The average of the numbers or dates in the array.
 */

export function average<T>(array: T[], callback?: (item: T) => number | Date): number | Date | undefined {
  if (array.length === 0) return undefined;

  // Check if we are dealing with Dates (either directly or via callback)
  const firstItem = callback ? callback(array[0]) : array[0];
  const isDate = firstItem instanceof Date;

  if (isDate) {
    const totalTimestamp = array.reduce<number>((acc, item) => {
      const val = callback ? callback(item) : item;
      if (!(val instanceof Date)) {
        throw new TypeError('average expected all items to be Date objects');
      }
      return acc + val.getTime();
    }, 0);
    return new Date(totalTimestamp / array.length);
  }

  // Handle numbers
  try {
    const total = sum(array, callback as (item: T) => number);
    if (typeof total === 'number') {
      return total / array.length;
    }
  } catch (err) {
    if (err instanceof TypeError) return undefined;
    throw err;
  }

  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 undefined if 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); // 30

With 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); // 6

Averaging 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-03

Handling Empty Data

ts
import { average } from '@vielzeug/toolkit';

const result = average([]); // undefined

Implementation Notes

  • Internally leverages the sum utility to calculate the total before dividing by the array length.
  • Does not automatically filter out null or undefined values; ensure your input array contains only numbers for accurate results.
  • Throws TypeError if the input is not an array.

See Also

  • sum: Calculate the total of an array of numbers.
  • median: Find the middle value in a set of numbers.
  • round: Round the average result to a specific precision.