Iterator and Generator Fundamentals

Video

JavaScript Notes

JavaScript
    // ES6 Iterator and Generator Fundamentals
    // Arrays, Strings, Maps, Sets, NodeLists – built-in iterators
    // {Object} = > Iterator = > Generator
    // Generators are like wrappers around Iterators (syntactic sugar), that also allow you to return iterables in a certain order
    
    let log = console.log;
    let characters = ['Finn', 'Poe', 'Rey', 'Kylo', 'Luke', 'Leia']
    function* genny( ){	    // * denotes generator
        yield 'a';	        // yield is similar to return
        return undefined;
    }
    
    let iter = genny( );
    log(iter.next( ));	    // iterators have a next method - this will first return 'a'
    log(iter.next( ));      // running this a second time will return 'undefined'
    
    let starwars8 = {
        title: 'The Last Jedi', 
        director: 'Rian Johnson', 
        year: 2017,
        boxOffice: '1.3B',
    };
    
    for(let p of starwars 8{	// objects are not iterable!
    
    }
    
    let count = -1; 
    let SW8 = {
        [Symbol.iterator]: function(obj){	// object has one property! 
            return {
                next: ( ) => {
                    count++; 
                    switch (count) {
                        case 0:
                            return {
                                    value: obj.title,
                                    done: false }
                        case 1:
                            return {
                                    value: obj.year,
                                    done: false }
                        case 2:
                            return {
                                    value: obj.director,
                                    done: false }
                        case 3:
                            return {
                                    value: undefined,
                                    done: true }
                        default:
                            return {
                                    value: undefined,
                                    done: true }
                    }
                }
            }
        }
    };

    
    let data = SW8[Symbol.iterator] (starwars8);
    log(data.next( ));	// returns ‘The Last Jedi’, and false
    log(data.next( ));	// returns 2017, and false
    log(data.next( ));	// returns ‘Rian Johnson’, and false
    log(data.next( ));	// returns undefined, and true
    log(data.next( ));	// returns undefined, and true