/*
* Define an iterator that will return as the value of next the value of the preceding index N number of times
* so if [1, 2, 2, 4] was passed it would return 2 once for the first call, and then return 4 twice for the second * and third call
*
* Example:
* const iterator = new Iterator([1, 2, 2, 4]);
* iterator.next() -> 2
* iterator.next() -> 4
* iterator.next() -> 4
* iterator.next() -> null
*/
function iterator(arr) {
return {
currentCount: arr[0],
currentIndex: 0,
value: arr[1],
next: function() {
if (this.currentCount == 0) {
if (this.currentIndex+2 >= arr.length) {
return;
}
this.currentIndex += 2;
while (arr[this.currentIndex] == 0 && this.currentIndex+2 < arr.length) {
this.currentIndex += 2;
}
this.currentCount = arr[this.currentIndex];
this.value = arr[this.currentIndex+1];
}
// if after the while loop the very last element is valid but has 0, we want to set the value to undefined
if (this.currentCount > 0) {
this.currentCount--;
} else {
this.value = undefined;
}
return this.value;
}
};
}
// Inspect Console to see results. Run clear()
console.log('-- NEW TEST RUN --');
// Test cases
var Iterator = new iterator([1,2,2,4]);
console.log(Iterator.next()); // 2
console.log(Iterator.next()); // 4
console.log(Iterator.next()); // 4
console.log(Iterator.next()); // null/undefined
console.log(Iterator.next());// null/undefined
console.log('-- NEW TEST RUN --');
Iterator = new iterator([0,2,0,4,0,3]);
console.log(Iterator.next()); // null/undefined
console.log(Iterator.next()); // null/undefined
console.log('-- NEW TEST RUN --');
Iterator = new iterator([0,2,1,4,0,3,2,5,0,6]);
console.log(Iterator.next()); // 4
console.log(Iterator.next()); // 5
console.log(Iterator.next()); // 5
console.log(Iterator.next()); // null/undefined
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.