Skip to content

Instantly share code, notes, and snippets.

@rinster
Last active August 3, 2023 19:59
Show Gist options
  • Save rinster/6e42dabf4673b61ec3806be808e1504d to your computer and use it in GitHub Desktop.
Save rinster/6e42dabf4673b61ec3806be808e1504d to your computer and use it in GitHub Desktop.
class NestedIterator {
constructor(nestedList) {
this.stack = [];
this.indexStack = [];
this.nextElement = null;
this.stack.push(nestedList[0]);
this.indexStack.push(0);
}
hasNext() {
while (this.stack.length > 0) {
const list = this.stack[this.stack.length - 1];
const index = this.indexStack[this.indexStack.length - 1];
if (index < list.length) {
const nextElement = list[index];
this.indexStack[this.indexStack.length - 1]++;
if (!isNaN(nextElement) && !Array.isArray(nextElement)) {
// If the next value is an integer,
// store it in 'nextElement' and return true
this.nextElement = nextElement;
return true;
} else {
// If the next value is a nested list,
// push it to the stack for further traversal
this.stack.push(nextElement);
this.indexStack.push(0);
}
} else {
// If the current list is fully traversed,
// pop it from the stack
this.stack.pop();
this.indexStack.pop();
}
}
return false;
}
next() {
if (this.hasNext()) {
// If there is a next element, store it in 'val'
// and reset 'nextElement' to null
const val = this.nextElement;
this.nextElement = null;
return val;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment