Skip to content

Commit

Permalink
add iterators generators lecture
Browse files Browse the repository at this point in the history
  • Loading branch information
15Dkatz committed Feb 12, 2017
1 parent 6b49935 commit 0bd7497
Show file tree
Hide file tree
Showing 3 changed files with 76 additions and 0 deletions.
54 changes: 54 additions & 0 deletions app/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
// // part 1:
// const arrayIterator = (array) => {
// let index = 0;
//
// return {
// next: () => {
// if (index < array.length) {
// let next = array[index];
// index += 1;
// return next;
// }
// }
// }
// }
//
// var it = arrayIterator([1, 2, 3]);
// console.log(it.next());
// console.log(it.next());
// console.log(it.next());
// console.log(it.next());

// // part 2:
// function* arrayIterator() {
// yield arguments;
// }
//
// var it = arrayIterator(1, 2, 3);
// console.log(it.next().value);

// // part 3:
// function* arrayIterator() {
// for (let arg of arguments) {
// yield arg
// }
// }
//
// var it = arrayIterator(1, 2, 3);
//
// // part 4:
// function* arrayIterator() {
// yield* arguments;
// }
//
// var it = arrayIterator(1, 2, 3);
//
// // part 5:
// var array = [1, 2, 3];
// var it = arrayIterator(...array);
//
// // parts 2-5:
// console.log(it.next().value);
// console.log(it.next().value);
// console.log(it.next().value);
// console.log(it.next().value);
22 changes: 22 additions & 0 deletions app/script.txt_iterators_generators
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
// TODO add to google doc.

console.log(it.next().value);
console.log(it.next().value);
console.log(it.next().value);
console.log(it.next().value); With some console.logs to it now
we find that the iterator yields each argument within arguments
individually.

Note that we've essentially used the yield keyword 3 times in this loop
and es6 provides a shortcut for us whenever we use yield more than one time in a row.
We can just use the yield asterisk syntax and reform the for loop to one line with:
yield* arguments; And you'll notice in our console that everything works the same!

Great! now to transform the arguments in arrayIterator to a true array and fully mimic
the iterator we created originally we could just pass a spread array rather than arguing each
element one a a time, and boom we have a fully mimicked iterator with es6 generators.

Awesome! This covered a more advanced topic within JavaSCript and es6 in general.
And if you plan on coding in languages in more than just JS and ES6, then iterators will show up everywhere.
Most of all though, generators will allow you to approach more advanced programs in ES6,
expecially with the convenient yield keyword and next method!
Empty file.

0 comments on commit 0bd7497

Please sign in to comment.