All files / src/components/groupedGrandChild updateDisplaySequence.ts

5.4% Statements 2/37
0% Branches 0/20
0% Functions 0/2
5.55% Lines 2/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    66x   66x                                                                                                          
import { SortedRecordProps } from "@props/RecordProps";
 
const STEP = 10;
 
export const updateDisplaySequence = <T extends SortedRecordProps>(data: T[], newIndex: number): [T[], T[]] => {
  const changedElements: T[] = [];
  const newData = data.slice();
  if (data.length < 2) {
    return [newData, changedElements];
  }
  const current = newData[newIndex];
  // this function will re calculate all element's displaySequence to satisfy the sequence.
  const reCalculate = (): void => {
    let previousDisplaySequence = -1;
    for (let i = 0; i < newData.length; ++i) {
      if (previousDisplaySequence >= newData[i].displaySequence) {
        newData[i].displaySequence = previousDisplaySequence + STEP;
        changedElements.push(newData[i]);
      }
      previousDisplaySequence = newData[i].displaySequence;
    }
  };
  if (newIndex === newData.length - 1) {
    // if the target is the last element
    if (current.displaySequence > newData[newIndex - 1].displaySequence) {
      return [newData, changedElements];
    }
    current.displaySequence = newData[newIndex - 1].displaySequence + 10;
    changedElements.push(current);
 
  } else if (newIndex === 0) {
    // if the target is the first element
    if (current.displaySequence < newData[newIndex + 1].displaySequence) {
      return [newData, changedElements];
    }
    current.displaySequence = newData[newIndex + 1].displaySequence - 10;
    if (current.displaySequence < 0) {
      reCalculate();
    } else {
      changedElements.push(current);
    }
  } else {
    const prev = newData[newIndex - 1];
    const next = newData[newIndex + 1];
    if (prev.displaySequence < current.displaySequence && current.displaySequence < next.displaySequence) {
      return [newData, changedElements];
    }
    const mid = Math.floor((next.displaySequence + prev.displaySequence) / 2);
    if (mid > prev.displaySequence) {
      current.displaySequence = mid;
      changedElements.push(current);
    } else {
      reCalculate();
    }
  }
  return [newData, changedElements];
};