All files / array/src normalizeIndex.ts

100% Statements 8/8
100% Branches 1/1
100% Functions 3/3
100% Lines 8/8

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 28 29 301x                                     5x 1x 5x 5x 5x 5x     5x    
import { mod } from "@benneq/number";
import { RelativeIndex } from "./_types";
 
/**
 *
 * @example
 * ```ts
 * const array = [1, 2, 3];
 * const index = -5;
 *
 * const normalizedIndex = normalizeIndex(index)(array);
 *
 * console.log(normalizedIndex); // 1
 * ```
 *
 * @param array
 * @param index
 * @returns the normalized index, or `0` if the array is empty
 */
export const normalizeIndex =
  (index: RelativeIndex) =>
  (array: ArrayLike<unknown>): number => {
    if (process.env.NODE_ENV !== "production") {
      console.assert(index >= -array.length);
      console.assert(index < array.length);
    }
 
    return mod(index, array.length);
  };