Last active
January 26, 2019 17:37
-
-
Save antoniojps/1e395364f0334c7290b16dd130229c61 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // ITERATORS | |
| // Exemplo de modificar o iterator para adicionar uma string 'is Sexy' | |
| // sempre que utilizamos um for of loop | |
| let myArray = ['Antonio', 'Toze', 'Toninho']; | |
| myArray[Symbol.iterator] = function() { | |
| let index = -1; | |
| const length = this.length; | |
| const arr = this; | |
| return { | |
| next: function() { | |
| index++; | |
| return { | |
| done: index > length - 1 ? true : false, | |
| value: arr[index] + ' is Sexy' | |
| }; | |
| } | |
| }; | |
| } | |
| //-for..of loop; | |
| for (let element of myArray) { | |
| console.log(element); | |
| } | |
| // "Antonio is Sexy" | |
| // "Toze is Sexy" | |
| // "Toninho is Sexy" | |
| // ITERATOR COSTUM | |
| // For of loop through persons hobbies | |
| const person = { | |
| name: 'Antonio', | |
| hobbies: ['surf', 'gaming', 'coding'], | |
| [Symbol.iterator]: function() { | |
| let index = 0 | |
| const hobbies = this.hobbies | |
| return { | |
| next: function () { | |
| const hobbie = hobbies[index] | |
| index += 1 | |
| return { | |
| done: index > hobbies.length ? true : false, | |
| value: hobbie | |
| } | |
| } | |
| } | |
| } | |
| } | |
| for (let hobby of person) { | |
| console.log(hobby) | |
| } | |
| // "surf" | |
| // "gaming" | |
| // "coding" | |
| // GENERATORS | |
| // generator function marked with * | |
| // generates iterator | |
| function* gen(end) { | |
| for (let i = 0; i < end; i++) { | |
| try { | |
| yield i | |
| } catch (err) { | |
| console.log(`error message - ${err}`) | |
| } | |
| } | |
| } | |
| const it = gen(3) | |
| console.log(it.next()) | |
| console.log(it.throw('MonkaS')) | |
| console.log(it.next()) | |
| console.log(it.next()) | |
| /* | |
| [object Object] { | |
| done: false, | |
| value: 0 | |
| } | |
| "error message - MonkaS" | |
| [object Object] { | |
| done: false, | |
| value: 1 | |
| } | |
| [object Object] { | |
| done: false, | |
| value: 2 | |
| } | |
| [object Object] { | |
| done: true, | |
| value: undefined | |
| } | |
| */ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment