JSFiddle - React, Tailwind, and code Playground
by poonia
HTML
<div id="result">0</div>
<button id="next">Next</button>
<button id="hasNext">Has Next</button>
JavaScript
test = [1,2,[3,4],5,[6,[7,8]],9,[[[]]],10];
function printOnPage(val) {
document.getElementById("result").innerHTML = val;
}
var FlatIterator = function(initalArray) {
var array = initalArray;
var secretNext;
var stack = [{
array: initalArray,
pos: 0
}];
this.next = function() {
if (secretNext) {
var retValue = secretNext;
secretNext = null;
return retValue;
}
var stackPeek = stack[stack.length-1];
if (stackPeek) {
var array = stackPeek.array;
var position = stackPeek.pos;
if (position < array.length) {
var item = array[position];
stackPeek.pos = stackPeek.pos + 1;
// If array
if (Object.prototype.toString.call(item) === "[object Array]") {
stack.push({
array: item,
pos: 0
});
return this.next();
} else {
return item;
}
} else {
stack.pop();
return this.next();
}
}
}
var peekSecretly = function() {
if (!secretNext) {
secretNext = this.next();
}
return secretNext;
}
this.hasNext = function() {
return !!peekSecretly.apply(this);
}
this.printNext = function() {
printOnPage(this.next());
}
this.printHasNext = function() {
printOnPage(this.hasNext());
}
}
it = new FlatIterator(test);
document.getElementById("next").addEventListener('click', it.printNext.bind(it));
document.getElementById("hasNext").addEventListener('click', it.printHasNext.bind(it));