Skip to content

Instantly share code, notes, and snippets.

@basekays
Created June 19, 2018 22:04
Show Gist options
  • Select an option

  • Save basekays/e056f4fc61b67afa288f56e0ec43dabd to your computer and use it in GitHub Desktop.

Select an option

Save basekays/e056f4fc61b67afa288f56e0ec43dabd to your computer and use it in GitHub Desktop.
/**
* 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