Generators Flashcards
What is the for of loop for?
Iterating through arrays of data
const colors = [‘red’, ‘green’, ‘blue’];
for (let color of colors){
console.log(color);
}
const numbers = [1,2,3,4]
let total = 0; for(let number of numbers){ total +=number; }
What is a generator?
A generator is a function that can be entered and exited multiple times
Normally - when we run a function the function will run and it returns some value and that’s it
With generators, you can return a value and then return back to the place where you left off.
What’s a good generator story?
function\* shopping(){ // stuff on the sidewalk
// walking down the sidewalk
// go into the store with cash const stuffFromStore = yield 'cash'; // CHANGES TO const stuffFromStore = 'groceries'; // continue to laundry place const cleanClothes = yield 'laundry'; // CHANGES to const cleanClothes = 'clean clothes';
// walking back home return [stuffFromStore, cleanClothes]; }
// stuff in the store const gen = shopping(); // leaving our house, we must call gen.next(), we start executing code in function gen.next();
// walked into the store // walking up and down the aisles.. // purchase our stuff
gen. next(‘groceries’); // leaving the store with groceries
gen. next(‘clean clothes’);
What is the BIG REVEAL with generators? What do they work well with?
For of loops.
We can use generators to iterate through any data structure that we want
const engineeringTeam = { size:3, department: 'Engineering', lead: 'Jill', manager: 'Alex', engineer: 'Dave' };
function* TeamIterator(team){
yield team.lead;
yield team.manager;
yield team.engineer;
}
const names = []; for(let name of TeamIterator(engineeringTeam)){ names.push(name); }
names
What is generator delegation?
There is an engineering team, theree is a lead manager engineer BUT also testing team, but the testing team has their own stand alone thing, own lead and own tester.
Testing team could be supporting multiple engineering teams.
yield* is our generator delegator
What is a symbol iterator?
Tool that teaches objects how to respond to the for of loop