Created
August 10, 2021 00:38
-
-
Save churchofthought/1383cb7b8ca7df89aa644181e39139fb to your computer and use it in GitHub Desktop.
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
// write iterator class MyIterator(input) | |
// that has hasNext(), and next(), and can appropriately deal with multidimensional arrays | |
class MyIterator { | |
#stack | |
#cachedNext | |
#hasNext = false | |
constructor(input){ | |
this.#stack = [input.values()] | |
} | |
hasNext(){ | |
if (this.#hasNext){ | |
return true | |
} | |
try { | |
this.#cachedNext = this.next() | |
return (this.#hasNext = true) | |
} catch (e) { | |
return (this.#hasNext = false) | |
} | |
} | |
next(){ | |
if (this.#hasNext){ | |
this.#hasNext = false | |
return this.#cachedNext | |
} | |
while (this.#stack.length){ | |
const iterator = this.#stack[this.#stack.length - 1] | |
const next = iterator.next() | |
if (next.done){ | |
this.#stack.pop() | |
continue | |
} | |
const val = next.value | |
if (val instanceof Array){ | |
this.#stack.push(val.values()) | |
continue | |
} | |
return val | |
} | |
throw "Error, no more array elements exist" | |
} | |
} | |
console.log('Iterating Test Case 1') | |
const it = new MyIterator([ | |
[2,4], | |
[6,[8,10],12], | |
[[[14]]], | |
[],[],[undefined], | |
16 | |
]) | |
while (it.hasNext()){ | |
console.log(it.next()) | |
} | |
console.log('Iterating Test Case 2') | |
const it2 = new MyIterator([ | |
[1,2,3,4,5], | |
[6,[7,8,[9],10],12], | |
[[[13,14,[15]]]], | |
[],[16],[undefined], | |
null, | |
NaN | |
]) | |
while (it2.hasNext()){ | |
it2.hasNext();it2.hasNext();it2.hasNext() | |
console.log(it2.next()) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment