Avenger
Avenger

Reputation: 1

Uncaught TypeError: Cannot read properties of undefined (reading 'style') error

i'm making a sorting visualizer project and i followed a tutorial for the mergeSort algorithm and now i'm trying to make the quicksort algorithm my self. i wrote the code the algorithm works fine but when i try to visualize it i get the error listed in the title if this question and i don't know why the error accures at line const barOneStyle = arrayBars[barOneidx].style; in the visualizer code

here is the code for the visualizer:

quickSort() {
    const animations = QuickSort.quickSort(this.state.array);
    const newAnimations = [];

    for(const animation of animations){
        newAnimations.push(animation.swap);
    }


    for(let i = 0; i < newAnimations.length; i++){
        const arrayBars = document.getElementsByClassName('array-bar');          
        
        setTimeout(() => {
            const [barOneidx, newHeight] = newAnimations[i];
            const barOneStyle = arrayBars[barOneidx].style;
            barOneStyle.height = `${newHeight}px`;
        }, i * 2);

    }
}

and here is the code for the algorithm:

   export const quickSort = array => {
   const animations = [];
   if (array.length <= 0) return;
   sortHelper(array, 0, array.length - 1, animations);
   return animations;
   };

   function sortHelper(mainArray, startIdx, endIdx, animations) {
   if (endIdx <= startIdx) return;
   let index = partition(mainArray, startIdx, endIdx, animations);
   sortHelper(mainArray, startIdx, index - 1, animations);
   sortHelper(mainArray, index + 1, endIdx, animations);
   }

   function partition(array, startIdx, endIdx, animations){
   const animation = {};
   let pivotIndex = startIdx;
   let pivotValue = array[endIdx];
   for(let i = startIdx; i < endIdx; i++){
    if(array[i] < pivotValue){
       animation.swap = swap(array, i, pivotIndex, animations);
       pivotIndex++;
     }
   }

   animation.swap = swap(array, pivotIndex, endIdx, animations);

   animations.push(animation);
   return pivotIndex;
 }

 function swap(arr, a, b, animations){
   let temp = arr[a];
   arr[a] = arr[b];
   arr[b] = temp;

   animations.push({ swap: [a, arr[a]] });
   animations.push({ swap: [b, arr[b]] });

   return animations;
 }

i already have seen other questions similar like this but none of them have helped me and i'm new to this so i dont know what'st causing it

Upvotes: 0

Views: 1237

Answers (0)

Related Questions