Skip to content

Instantly share code, notes, and snippets.

@getify
Last active Oct 15, 2017
Embed
What would you like to do?
generators as object iterator
// 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
// 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