diff --git "a/leetcode3/\354\240\225\354\247\204\354\230\201/284. Peeking Iterator" "b/leetcode3/\354\240\225\354\247\204\354\230\201/284. Peeking Iterator" new file mode 100644 index 00000000..bb2cf35f --- /dev/null +++ "b/leetcode3/\354\240\225\354\247\204\354\230\201/284. Peeking Iterator" @@ -0,0 +1,56 @@ +/** + * // This is the Iterator's API interface. + * // You should not implement it, or speculate about its implementation. + * function Iterator() { + * @ return {number} + * this.next = function() { // return the next number of the iterator + * ... + * }; + * + * @return {boolean} + * this.hasNext = function() { // return true if it still has numbers + * ... + * }; + * }; + */ + +/** + * @param {Iterator} iterator + */ +var PeekingIterator = function(iterator) { + this.iterator = iterator; + + this.nextValue = iterator.hasNext() ? iterator.next() : null; +}; + +/** + * @return {number} + */ +PeekingIterator.prototype.peek = function() { + return this.nextValue; +}; + +/** + * @return {number} + */ +PeekingIterator.prototype.next = function() { + const ans = this.nextValue; + + this.nextValue = this.iterator.hasNext() ? this.iterator.next() : null; + return ans; +}; + +/** + * @return {boolean} + */ +PeekingIterator.prototype.hasNext = function() { + return this.nextValue !== null; +}; + +/** + * Your PeekingIterator object will be instantiated and called as such: + * var obj = new PeekingIterator(arr) + * var param_1 = obj.peek() + * var param_2 = obj.next() + * var param_3 = obj.hasNext() + */