Last active
January 28, 2019 03:15
-
-
Save lahin31/e491cabf0064316805cb386e2a25860e to your computer and use it in GitHub Desktop.
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
/** | |
* 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