Skip to content

Instantly share code, notes, and snippets.

@jclem
Last active August 29, 2015 14:21
Show Gist options
  • Save jclem/fbd44c43cb175dbf880e to your computer and use it in GitHub Desktop.
Save jclem/fbd44c43cb175dbf880e to your computer and use it in GitHub Desktop.
Scanner
class Scanner {
constructor(array) {
this.idx = 0;
this.array = array;
this.stack = [this];
this.prev = null;
}
next() {
const scanner = this.stack[this.stack.length - 1];
if (!scanner) {
return null;
}
const next = scanner.array[scanner.idx];
scanner.idx++;
if (Array.isArray(next)) {
this.stack.push(new Scanner(next));
return this.next();
} else if (!next) {
this.stack.pop();
return this.next();
} else {
const prev = this.prev;
this.prev = next;
return [prev, next];
}
}
}
const array = [1, 2, [3, [4], 5], 6, [7, [8, 9]], 10];
const scanner = new Scanner(array);
let pair;
while ((pair = scanner.next()) !== null) {
console.log('pair', pair);
i++;
}
console.log('Done!');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment