Iterator Example

Share

Iterator Example

This is a poor example as you could certainly accomplish this more easily with .map(), however, this demonstrates that the iterator ‘remembers’ its position and picks up where it left off. A better example would be where other procedures or logic are executed between calls.

function makeIterator(array) {
    var nextIndex = 0;
    return {
        next: ()=>(nextIndex < array.length) && array[nextIndex++],
        remain: ()=>array.length - nextIndex
    }
}
var fun = makeIterator(['fe', 'fi', 'fo', 'fum', 'I', 'smell']);

while(fun.remain()){
    console.log(fun.next());
}
Share

Leave a Reply

Your email address will not be published. Required fields are marked *