All files / array/src insertAt.ts

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

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 30 31 32                                          4x 1x 4x 4x 4x 4x     4x    
import { RelativeIndex } from "./_types";
 
/**
 * Inserts values into an Array at the specified index
 *
 * @mutation
 *
 * @example
 * Insert values `4` and `5` at index `1`
 * ```ts
 * const array = [1, 2, 3];
 *
 * insertAt(1, 4, 5)(array);
 *
 * console.log(array); // 1, 4, 5, 2, 3
 * ```
 *
 * @typeParam T - the {@link Array} element type
 * @param index - the index to insert the `values`
 * @param values - the values to insert
 */
export const insertAt =
  <T>(index: RelativeIndex, ...values: T[]) =>
  (array: T[]): void => {
    if (process.env.NODE_ENV !== "production") {
      console.assert(index >= -array.length);
      console.assert(index < array.length);
    }
 
    array.splice(index, 0, ...values);
  };