Skip to content

Instantly share code, notes, and snippets.

@rnaffer
Created June 15, 2017 00:31
Show Gist options
  • Save rnaffer/b1fc70d7d49e43e67417acd24f071470 to your computer and use it in GitHub Desktop.
Save rnaffer/b1fc70d7d49e43e67417acd24f071470 to your computer and use it in GitHub Desktop.
Cómo construir mi propio iterador
// Iterador que empieza sobre el índice indicado como parámetro
// ¿Por qué yield?
Array.prototype.myIterator = function* (startIdx = 0) {
while (startIdx < this.length) {
if (this.hasOwnProperty(startIdx)) {
yield [this[startIdx], startIdx];
}
startIdx++;
}
};
// Forma de usarlo
// empieza a iterar en el índice 1
for (var [val, idx] of [0,2,4,6,8].myIterator(1)) {
console.log(val, idx);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment