Last active
August 29, 2015 14:21
-
-
Save jclem/fbd44c43cb175dbf880e to your computer and use it in GitHub Desktop.
Scanner
This file contains 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
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