Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

206
Views
Solve Weave using recursion in JS

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

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!