Skip to content

Instantly share code, notes, and snippets.

@hovissimo
Last active February 28, 2016 09:54
Show Gist options
  • Save hovissimo/a55eae68f96964690629 to your computer and use it in GitHub Desktop.
Save hovissimo/a55eae68f96964690629 to your computer and use it in GitHub Desktop.
Some ES6 that will make all objects directly iterable in a convenient but utterly unrecommended way.
Object.prototype[Symbol.iterator] = function() {
iterator = {
values: Object.keys(this).map((function (k) {
return [k, this[k]];
}).bind(this)),
next: function() {
if (this.values.length <= 0) {
return {done: true};
} else {
return {value: this.values.shift(), done:false};
}
}
}
return iterator;
}
let o = {a:5, b:6, c:7};
for (let [k, v] of o) {
console.log(`${k} is ${v}`);
}
// Output:
// a is 5
// b is 6
// c is 7
@hovissimo
Copy link
Author

Implemented with the ugly values array so it could run in my browser. May as well use an actual generator though.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment