Last active
February 28, 2016 09:54
-
-
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.
This file contains hidden or 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
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Implemented with the ugly values array so it could run in my browser. May as well use an actual generator though.