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
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 !