Skip to content

Commit 491c2de

Browse files
authored
Implement PeekingIterator for iterator functionality
1 parent c56cc52 commit 491c2de

1 file changed

Lines changed: 56 additions & 0 deletions

File tree

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
/**
2+
* // This is the Iterator's API interface.
3+
* // You should not implement it, or speculate about its implementation.
4+
* function Iterator() {
5+
* @ return {number}
6+
* this.next = function() { // return the next number of the iterator
7+
* ...
8+
* };
9+
*
10+
* @return {boolean}
11+
* this.hasNext = function() { // return true if it still has numbers
12+
* ...
13+
* };
14+
* };
15+
*/
16+
17+
/**
18+
* @param {Iterator} iterator
19+
*/
20+
var PeekingIterator = function(iterator) {
21+
this.iterator = iterator;
22+
23+
this.nextValue = iterator.hasNext() ? iterator.next() : null;
24+
};
25+
26+
/**
27+
* @return {number}
28+
*/
29+
PeekingIterator.prototype.peek = function() {
30+
return this.nextValue;
31+
};
32+
33+
/**
34+
* @return {number}
35+
*/
36+
PeekingIterator.prototype.next = function() {
37+
const ans = this.nextValue;
38+
39+
this.nextValue = this.iterator.hasNext() ? this.iterator.next() : null;
40+
return ans;
41+
};
42+
43+
/**
44+
* @return {boolean}
45+
*/
46+
PeekingIterator.prototype.hasNext = function() {
47+
return this.nextValue !== null;
48+
};
49+
50+
/**
51+
* Your PeekingIterator object will be instantiated and called as such:
52+
* var obj = new PeekingIterator(arr)
53+
* var param_1 = obj.peek()
54+
* var param_2 = obj.next()
55+
* var param_3 = obj.hasNext()
56+
*/

0 commit comments

Comments
 (0)