Created
March 4, 2019 15:59
-
-
Save kaid/81d47483fb1cdf92f562da614eca1a76 to your computer and use it in GitHub Desktop.
BFE学习小分队习题
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 NestedIterator { | |
constructor(iteratee = []) { | |
this.stack = [[iteratee, 0]]; | |
} | |
getTop() { | |
const topIndex = this.stack.length - 1; | |
if (topIndex < 0) { | |
return null; | |
} | |
return this.stack[topIndex]; | |
} | |
setTop(v) { | |
const topIndex = this.stack.length - 1; | |
if (topIndex < 0) { | |
return null; | |
} | |
this.stack[topIndex] = v; | |
} | |
hasNext() { | |
const top = this.getTop(); | |
if (top === null) { | |
return false; | |
} | |
const [iteratee, cursor] = top; | |
return iteratee.length - 1 >= cursor; | |
} | |
next() { | |
const [iteratee, cursor] = this.getTop(); | |
const next = iteratee[cursor]; | |
if (cursor === iteratee.length - 1) { | |
this.stack.pop(); | |
} else { | |
this.setTop([iteratee, cursor + 1]); | |
} | |
if (next instanceof Array) { | |
if (next.length !== 0) { | |
this.stack.push([next, 0]); | |
} | |
return this.next(); | |
} | |
return next; | |
} | |
} | |
const v = [[], 2, [1,[]], [3, [4, [5, [], [], [[[], []], []], [6, 7, 8, 9, [10, [11, 12], 13], 14], 15], 16], 17]]; | |
const a = []; | |
const n = new NestedIterator(v); | |
while (n.hasNext()) { | |
// console.log(n.next(), JSON.stringify(n.stack), n.hasNext()); | |
a.push(Number(n.next())) | |
} | |
console.log(JSON.stringify(a)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment