Created
December 28, 2016 19:26
-
-
Save ronaiza-cardoso/9caa34eb1328a6c77d4784251fb9bcc5 to your computer and use it in GitHub Desktop.
Iterators and generators - simple file to test generator exemple from mozilla page
This file contains 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 | |
Um objeto é um iterator quando ele sabe como acessar os items de uma coleção um por vez enquanto mantém o endereço da posição | |
atual da sequencia. Em JavaScript um interator é um objeto que prové o método next() que retorna o próximo item da sequencia | |
esse método retorna um objeto com as sequintes propriedades: done e value. | |
*/ | |
function makeIterator(array){ | |
var nextIndex = 0; | |
return { | |
next: function(){ | |
return nextIndex < array.length ? | |
{value: array[nextIndex++], done: false} : | |
{done: true}; | |
} | |
} | |
} | |
/* | |
Uma vez inicializado, o método next() pode ser chamado para acessar o par chave-valor do objeto como retorno: | |
*/ | |
var it = makeIterator(['yo', 'ya']); | |
console.log(it.next().value); // 'yo' | |
console.log(it.next().value); // 'ya' | |
console.log(it.next().done); // true |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment