Skip to content

Instantly share code, notes, and snippets.

@lahin31
Last active January 28, 2019 03:15
Show Gist options
  • Save lahin31/e491cabf0064316805cb386e2a25860e to your computer and use it in GitHub Desktop.
Save lahin31/e491cabf0064316805cb386e2a25860e to your computer and use it in GitHub Desktop.
/**
* Custom Iterator
* Making an Object iterable by using for...of loop
* By Muhammad Lahin
*/
let obj = {
id: 1,
name: "John Cena",
profession: "Wrestling"
}
obj[Symbol.iterator] = function () {
let counter = -1;
return {
next: function () {
counter++;
switch (counter) {
case 0:
return { value: obj.id, done: false }
case 1:
return { value: obj.name, done: false }
case 2:
return { value: obj.profession, done: false }
default:
return { done: true }
}
}
}
}
for (let val of obj) {
console.log(val) // 1, John Cena, Wrestling
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment