-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathweave.js
More file actions
54 lines (49 loc) · 1.3 KB
/
weave.js
File metadata and controls
54 lines (49 loc) · 1.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
// --- Directions
// 1) Complete the task for weave
// 2) Implement the 'weave' function. Weave
// receives two queues as arguments and combines the
// contents of each into a new, third queue.
// The third queue should contain the *alterating* content
// of the two queues. The function should handle
// queues of different lengths without inserting
// 'undefined' into the new one.
// *Do not* access the array inside of any queue, only
// use the 'add', 'remove', and 'peek' functions.
// --- Example
// const queueOne = new Queue();
// queueOne.add(1);
// queueOne.add(2);
// const queueTwo = new Queue();
// queueTwo.add('Hi');
// queueTwo.add('There');
// const q = weave(queueOne, queueTwo);
// q.remove() // 1
// q.remove() // 'Hi'
// q.remove() // 2
// q.remove() // 'There'
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(Q1, Q2) {
const newQ = new Queue();
while (Q1.peek() !== undefined || Q2.peek() !== undefined){
if (Q1.peek() !== undefined){
newQ.add(Q1.remove())
}
if (Q2.peek() !== undefined){
newQ.add(Q2.remove())
}
}
return newQ
}