-
-
Save getify/f37e716dd3b3c19062db5a8cb4bd2804 to your computer and use it in GitHub Desktop.
generators as object iterator
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
// ugly way | |
var obj = { | |
a: 1, | |
b: 2, | |
c: 3, | |
[Symbol.iterator]() { | |
var keys = Object.keys(this); | |
var idx = 0; | |
return { | |
next: () => { | |
if (idx < keys.length) return { value: this[keys[idx++]], done: false }; | |
return { value: undefined, done: true }; | |
} | |
}; | |
} | |
}; | |
for (let v of obj) { | |
console.log( v ); | |
} | |
// 1 2 3 |
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
// better way, generators ftw! | |
var obj = { | |
a: 1, | |
b: 2, | |
c: 3, | |
*[Symbol.iterator]() { | |
for (let k of Object.keys(this)) { | |
yield this[k]; | |
} | |
} | |
}; | |
for (let v of obj) { | |
console.log( v ); | |
} | |
// 1 2 3 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment