I have this code after following one tutorial, but he didn’t test it unfortunately in the end:
class Queue {
constructor() {
this.data = [];
}
add(record) {
this.data.unshift(record);
}
remove() {
return this.data.pop();
}
peek() {
return this.data[this.data.length - 1];
}
}
function weave(sourceOne, sourceTwo) {
const q = new Queue();
while (sourceOne.peek() || sourceTwo.peek()) {
if (sourceOne.peek()) {
q.add(sourceOne.remove());
}
if (sourceTwo.peek()) {
q.add(sourceTwo.remove());
}
}
return q;
}
weave([1, 3, 5], [2, 4, 6]);
So, when I run this function with two arrays: I get the following error:
Uncaught TypeError: sourceOne.peek is not a function
at weave
How should I use this weave function if not with two arrays?
It appears that sourceOne
and sourceTwo
are supposed to be Queues (as defined by the class), otherwise I assume the creator would not have written code using the peek
method as shown.
You are attempting to pass arrays for the two arguments, but you should instead be passing Queues as arguments.
I am not sure what the intent of the weave
function is, but it appears to alternate the values of the original queues into a new one.
const q1 = new Queue();
q1.add(1);
q1.add(3);
q1.add(5);
const q2 = new Queue();
q2.add(2);
q2.add(4);
q2.add(6);
console.log(weave(q1, q2));
you get: { data: [ 6, 5, 4, 3, 2, 1 ] }
1 Like
Thanks Randell, I understand now. Yes, the intent was to alternate values of queues. I thought it could be used with arrays.
You could modify the Queue class to accept an optional array argument and have it create the queue.
class Queue {
constructor(arr) {
this.data = arr ?? [];
}
add(record) {
this.data.unshift(record);
}
remove() {
return this.data.pop();
}
peek() {
return this.data[this.data.length - 1];
}
}
function weave(sourceOne, sourceTwo) {
const q = new Queue();
while (sourceOne.peek() || sourceTwo.peek()) {
if (sourceOne.peek()) {
q.add(sourceOne.remove());
}
if (sourceTwo.peek()) {
q.add(sourceTwo.remove());
}
}
return q;
}
const q1 = new Queue([5, 3, 1]);
const q2 = new Queue([6, 4, 2]);
console.log(weave(q1, q2)); // { data: [ 6, 5, 4, 3, 2, 1 ] }