Javascript Itertators

Shows how Javascript Iterators work

by Patrick Steranka

JavaScript

console.log('demo1 - show an iterator and first item in list');
let anEmptySet = new Set();
let aSet = new Set(['item1', 'item2', 'item3']);
demo1('Showing an EmptySet', anEmptySet);
demo1('aSet', aSet);

console.log('demo2 - Easiest way to loop over a collection (using iterator) (for of)');
demo2('anEmptySet', anEmptySet);
demo2('aSet', aSet);

console.log('demo3 - iterator using for() loop');
demo3('anEmptySet', anEmptySet)
demo3('aSet', aSet)

demo4('demo4 - iterator using while loop')
demo4('anEmptySet', anEmptySet)
demo4('aSet', aSet)


/* Show how to get an iterator */
function demo1(aMsg, aCollection){
    console.log('demo1: ' + aMsg);
    let it = aCollection[Symbol.iterator]();
    console.log('iterator is', it)
    console.log('it.done - is not meaningful', it.done); // notice that it.done is not defined!
    let itLoop = it.next()             // it
    console.log('it.next()', itLoop);
    console.log('it.next().value', itLoop.value);
    console.log('it.next().done', itLoop.done);
    console.log('\n\n');
}

function demo2(aMsg, aCollection){

    console.log('demo2: ' + aMsg);
    for(let item of aCollection){
        console.log('for of returns ', item);
    }
    console.log('\n\n');
}


function demo3(aMsg, aCollection){
    console.log('demo3: ' + aMsg);
    for(let it = aSet[Symbol.iterator](), loop = it.next(); ! loop.done; loop = it.next()){
        console.log('for with index ', loop.value);
    }
    console.log('\n\n');
}

function demo4(aMsg, aCollection){
    console.log('demo4: ' + aMsg);
    let it = aSet[Symbol.iterator]();
    let loop = it.next();
    while (! loop.done){
        console.log('for with index ', loop.value);
        loop = it.next();
    }
    console.log('\n\n');
}