Advertisement
Guest User

Untitled

a guest
Jun 25th, 2017
47
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.86 KB | None | 0 0
  1. // From Stephen Grider's Udemy course on ES6
  2. // We can use generators to iterate over any data-structure that we want
  3.  
  4. ---------------------
  5.  
  6. function* shopping() { // the * after "function" turns it into a generator
  7. // stuff on the sidewalk
  8.  
  9. // walking down the sidewalk
  10.  
  11. // go into the store with case
  12. const stuffFromStore = yeild 'cash';
  13.  
  14. // walking back home
  15. return stuffFromStore
  16. }
  17.  
  18. // stuff in the store
  19. const gen = shopping();
  20. gen.next(); // leaving our house
  21. // walked into the store
  22. gen.next('groceries') // leaving the store with groceries
  23.  
  24. ---------------------
  25.  
  26. function* colors() {
  27. yield 'red';
  28. yeild 'blue';
  29. yeild 'green';
  30. }
  31.  
  32. const myColors = [];
  33. for (let color of colors()) {
  34. myColors.push(color);
  35. }
  36. myColors; // ["red", "blue", "green"]
  37.  
  38. ---------------------
  39.  
  40. const engineeringTeam = {
  41. size: 3,
  42. department: 'Engineering',
  43. lead: 'Jill',
  44. manager: 'Alex',
  45. engineer: 'Dave'
  46. };
  47.  
  48. function* TeamIterator(team) {
  49. yeild team.lead;
  50. yeild team.manager;
  51. yeild team.engineer;
  52. }
  53.  
  54. const names = [];
  55. for (let name of TeamIterator(engineeringTeam)) {
  56. names.push(name);
  57. }
  58. console.log(names) // ["Jill", "Alex", "Dave"]
  59.  
  60. ---------------------
  61.  
  62. const testingTeam = {
  63. lead: 'Amanda',
  64. tester: 'Bill',
  65. [Symbol.iterator]: function* () { // Special object that tells the for of loop how it should iterate over the object
  66. yield this.lead;
  67. yield this.tester;
  68. }
  69. };
  70.  
  71. const engineeringTeam = {
  72. testingTeam,
  73. size: 3,
  74. department: 'Engineering',
  75. lead: 'Jill',
  76. manager: 'Alex',
  77. engineer: 'Dave',
  78. [Symbol.iterator]: function* () [
  79. yield this.lead;
  80. yield this.manager;
  81. yield this.engineer;
  82. yield* this.testingTeam; // This tells the for of loop it also needs to walk through the testingTeam
  83. };
  84.  
  85. const names = [];
  86. for (let name of engineeringTeam) {
  87. names.push(name);
  88. }
  89. console.log(names) // ["Jill", "Alex", "Dave", "Amanda", "Bill"]
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement