rotLeft

    0

    0

    This function rotates elements of an array left by d positions. The copy of the array is first destructed and the resulting arrays are then swapped. The length of the original array is subtracted by 1 to keep track of the position of the last element, which is then accessed and the rotElementIndex is set to arrLength-d. The for loop traverses the original array from the first element to the last, and if the count variable is not equal to 0 and the rotElementIndex is within the arrLength-d positions of the last element, the lastElement is inserted into the newArr array. The function then returns the new array.

    function rotLeft(a, d) {
      let copy = [...a];
      let copy2 = [...a].pop();
      let newArr = [];
      let arrLength = a.length - 1;
      let lastElement = copy.pop();
      let count = 0;
      let rotElementIndex = arrLength - d;
      for (let i = 0; i < arrLength; i++) {
        if (count === 0 && i===rotElementIndex) {
            newArr.push(lastElement);
            count++;
            i--;
        } else {
          newArr.push(a[i]);
        }
      }
      return(newArr);
    }
    Codiga Logo
    Codiga Hub
    • Rulesets
    • Playground
    • Snippets
    • Cookbooks
    soc-2 icon

    We are SOC-2 Compliance Certified

    G2 high performer medal

    Codiga – All rights reserved 2022.