0

We are given the following class


class Queue{

    constructor(){
        this.data=[];
    }

    add(record){
        this.data.unshift(record)
    }
    remove(){
        return this.data.pop()
    }
    peek(){
        // console.log()
        let lastElement=this.data[this.data.length-1]
        return lastElement;
     } 
}

without using any array features, we are required to write a weave function which will add elements alternatively as shown below enter image description here

The function looks like this (ie takes two arguments/queues as below)

function weave(sourceOne, sourceTwo) {}

I would like to know if we can solve this using recursion(not a while loop and we are not allowed to declare q3 * the new Queue outside the function),

the code I have written so far doesnt work as it initiates the new queue everytime the function is called ,


 let track =0

function weave(sourceOne, sourceTwo) {

    if(track>0){
        const q3 = new Queue()
    }
   track++

    //in simple language
  
    //while sourceOne.peek() is true keep adding
    
   
    if(sourceOne.peek()){
        q3.add(sourceOne.remove())
    }
    if(sourceTwo.peek()){
        q3.add(sourceTwo.remove())
    }
 
    console.log(q3)

   if (sourceTwo.peek()|| sourceOne.peek()){
       weave(sourceOne,sourceTwo)
   }
   
   else if( sourceTwo.peek()== null && sourceOne.peek()==null){
     
    return q3
   }
      
   }

The error is given below, thanks for any help !

enter image description here

Naveen DINUSHKA
  • 1,401
  • 3
  • 19
  • 32
  • A `const` defined inside a block is only available for reference inside the block. Define it outside instead. You probably want a third parameter that gets passed along recursively and default initialized to a Queue. – CertainPerformance May 08 '22 at 02:10

0 Answers0