Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

208
Visualizações
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
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda