iterator

random question

by Augustus Yuan

JavaScript

/* 
* 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