Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // From Stephen Grider's Udemy course on ES6
- // We can use generators to iterate over any data-structure that we want
- ---------------------
- function* shopping() { // the * after "function" turns it into a generator
- // stuff on the sidewalk
- // walking down the sidewalk
- // go into the store with case
- const stuffFromStore = yeild 'cash';
- // walking back home
- return stuffFromStore
- }
- // stuff in the store
- const gen = shopping();
- gen.next(); // leaving our house
- // walked into the store
- gen.next('groceries') // leaving the store with groceries
- ---------------------
- function* colors() {
- yield 'red';
- yeild 'blue';
- yeild 'green';
- }
- const myColors = [];
- for (let color of colors()) {
- myColors.push(color);
- }
- myColors; // ["red", "blue", "green"]
- ---------------------
- const engineeringTeam = {
- size: 3,
- department: 'Engineering',
- lead: 'Jill',
- manager: 'Alex',
- engineer: 'Dave'
- };
- function* TeamIterator(team) {
- yeild team.lead;
- yeild team.manager;
- yeild team.engineer;
- }
- const names = [];
- for (let name of TeamIterator(engineeringTeam)) {
- names.push(name);
- }
- console.log(names) // ["Jill", "Alex", "Dave"]
- ---------------------
- const testingTeam = {
- lead: 'Amanda',
- tester: 'Bill',
- [Symbol.iterator]: function* () { // Special object that tells the for of loop how it should iterate over the object
- yield this.lead;
- yield this.tester;
- }
- };
- const engineeringTeam = {
- testingTeam,
- size: 3,
- department: 'Engineering',
- lead: 'Jill',
- manager: 'Alex',
- engineer: 'Dave',
- [Symbol.iterator]: function* () [
- yield this.lead;
- yield this.manager;
- yield this.engineer;
- yield* this.testingTeam; // This tells the for of loop it also needs to walk through the testingTeam
- };
- const names = [];
- for (let name of engineeringTeam) {
- names.push(name);
- }
- console.log(names) // ["Jill", "Alex", "Dave", "Amanda", "Bill"]
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement