Created
June 19, 2018 22:04
-
-
Save basekays/e056f4fc61b67afa288f56e0ec43dabd to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /** | |
| * Return true if this NestedInteger holds a single integer, rather than a nested list. | |
| * @return {boolean} | |
| * this.isInteger = function() { | |
| * ... | |
| * }; | |
| * Return the single integer that this NestedInteger holds, if it holds a single integer | |
| * Return null if this NestedInteger holds a nested list | |
| * @return {integer} | |
| * this.getInteger = function() { | |
| * ... | |
| * }; | |
| * Return the nested list that this NestedInteger holds, if it holds a nested list | |
| * Return null if this NestedInteger holds a single integer | |
| * @return {NestedInteger[]} | |
| * this.getList = function() { | |
| * ... | |
| * }; | |
| * }; | |
| */ | |
| /** | |
| * @constructor | |
| * @param {NestedInteger[]} nestedList | |
| */ | |
| var NestedIterator = function(nestedList) { | |
| this.list = flattener(nestedList); | |
| this.index = 0; | |
| }; | |
| var flattener = function(list, flattened = []) { | |
| while (list.length) { | |
| var value = list.shift(); | |
| if (!value.isInteger()) { | |
| list = value.getList().concat(list); | |
| } else { | |
| flattened.push(value.getInteger()); | |
| } | |
| } | |
| return flattened; | |
| } | |
| /** | |
| * @this NestedIterator | |
| * @returns {boolean} | |
| */ | |
| NestedIterator.prototype.hasNext = function() { | |
| return this.index < this.list.length; | |
| }; | |
| /** | |
| * @this NestedIterator | |
| * @returns {integer} | |
| */ | |
| NestedIterator.prototype.next = function() { | |
| return this.list[this.index++]; | |
| }; | |
| /** | |
| * var i = new NestedIterator(nestedList), a = []; | |
| * while (i.hasNext()) a.push(i.next()); | |
| */ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment