All files / iterable/src avg.ts

100% Statements 6/6
100% Branches 4/4
100% Functions 2/2
100% Lines 5/5

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27                            2x         2x 3x 3x     2x    
/**
 * Calculates the average of all {@link number}s of an {@link Iterable}.
 *
 * @example
 * ```ts
 * const result = avg([1,2,3]);
 * console.log(result); // 2
 * ```
 *
 * @see {@link reduce} and {@link sum} for similar operations.
 *
 * @param iterable - the {@link Iterable} to average
 * @returns the average of all {@link number}s, or `undefined` if {@link Iterable} was empty
 */
export const avg = (
  iterable: Iterable<number>,
  length = 0,
  sum = 0
): number | undefined => {
  for (const value of iterable) {
    length++;
    sum += value;
  }
 
  return length ? sum / length : undefined;
};