All files / src/shared/lib/helpers array.ts

91.3% Statements 42/46
85% Branches 17/20
84.62% Functions 11/13
91.67% Lines 33/36

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 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 9329x   29x 1x       1x 1x 1x 1x       1x     29x       29x         10x               4x   6x 6x 6x     29x         12x 21x   12x 54x       12x       12x             29x       14x 30x 14x 37x 19x     29x         21x 21x 17x           4x      
import uniq from "lodash/uniq";
 
export const chunk = <T>(arr: T[], len?: number): T[][] => {
  Iif (!len) {
    return [arr];
  }
 
  const chunks: T[][] = [];
  const n = arr.length;
  let i = 0;
  while (i < n) {
    chunks.push(arr.slice(i, (i += len)));
  }
 
  return chunks;
};
 
export const filterUndefined = <T>(arr: (T | undefined)[]): T[] => {
  return arr.filter((t) => t !== undefined);
};
 
export const moveArrayElement = <T>(
  x: number,
  y: number,
  [...xs]: T[]
): T[] => {
  if (
    xs.length <= 1 ||
    x === y ||
    x < 0 ||
    x >= xs.length ||
    y < 0 ||
    y >= xs.length
  ) {
    return xs;
  }
  const [element] = xs.splice(x, 1);
  xs.splice(y, 0, element);
  return xs;
};
 
export const moveArrayElements = <T>(
  fromIndexes: number[],
  to: number,
  arr: T[]
): T[] => {
  const sortedIndexes = uniq([...fromIndexes].sort((a, b) => a - b));
  const selectedItems = sortedIndexes.map((index) => arr[index]);
 
  const remainingItems = arr.filter(
    (_, index) => !sortedIndexes.includes(index)
  );
 
  const adjustedIndex =
    to > sortedIndexes[sortedIndexes.length - 1]
      ? to - sortedIndexes.length + 1
      : to;
 
  return [
    ...remainingItems.slice(0, adjustedIndex),
    ...selectedItems,
    ...remainingItems.slice(adjustedIndex),
  ];
};
 
export const sortSubsetStringArray = (
  arr: string[],
  sortOrder: string[]
): string[] => {
  const orderMap = new Map<string, number>();
  sortOrder.forEach((element, index) => orderMap.set(element, index));
  return arr
    .filter((element) => orderMap.has(element))
    .sort((a, b) => (orderMap.get(a) ?? 0) - (orderMap.get(b) ?? 0));
};
 
export const insertAfterElement = <T>(
  arr: T[],
  insertElement: T,
  afterElement: T
): T[] => {
  const insertIndex = arr.indexOf(afterElement);
  if (insertIndex !== -1) {
    return [
      ...arr.slice(0, insertIndex + 1),
      insertElement,
      ...arr.slice(insertIndex + 1),
    ];
  } else {
    return arr.concat(insertElement);
  }
};