-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0281-zigzag-iterator.js
More file actions
49 lines (45 loc) · 1.54 KB
/
0281-zigzag-iterator.js
File metadata and controls
49 lines (45 loc) · 1.54 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
/**
* Zigzag Iterator
* Time Complexity: O(1)
* Space Complexity: O(K)
*/
var ZigzagIterator = function ZigzagIterator(v1Source, v2Source) {
this.firstVectorData = v1Source;
this.secondVectorData = v2Source;
this.firstVectorPointer = 0;
this.secondVectorPointer = 0;
this.shouldTakeFromFirst = true;
};
ZigzagIterator.prototype.hasNext = function hasNext() {
const hasMoreFromFirst =
this.firstVectorPointer < this.firstVectorData.length;
const hasMoreFromSecond =
this.secondVectorPointer < this.secondVectorData.length;
return hasMoreFromFirst || hasMoreFromSecond;
};
ZigzagIterator.prototype.next = function next() {
let elementToReturn;
const firstListHasElements =
this.firstVectorPointer < this.firstVectorData.length;
const secondListHasElements =
this.secondVectorPointer < this.secondVectorData.length;
if (firstListHasElements && secondListHasElements) {
if (this.shouldTakeFromFirst) {
elementToReturn = this.firstVectorData[this.firstVectorPointer];
this.firstVectorPointer++;
} else {
elementToReturn = this.secondVectorData[this.secondVectorPointer];
this.secondVectorPointer++;
}
this.shouldTakeFromFirst = !this.shouldTakeFromFirst;
} else if (firstListHasElements) {
elementToReturn = this.firstVectorData[this.firstVectorPointer];
this.firstVectorPointer++;
} else if (secondListHasElements) {
elementToReturn = this.secondVectorData[this.secondVectorPointer];
this.secondVectorPointer++;
} else {
return undefined;
}
return elementToReturn;
};