Generators Flashcards

1
Q

What is the for of loop for?

A

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;
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

What is a generator?

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

What’s a good generator story?

A
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’);

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

What is the BIG REVEAL with generators? What do they work well with?

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

What is generator delegation?

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

What is a symbol iterator?

A

Tool that teaches objects how to respond to the for of loop

How well did you know this?
1
Not at all
2
3
4
5
Perfectly