Last active
July 23, 2018 23:29
-
-
Save ericelliott/f62714425d4603c0101d49f87935e1bf to your computer and use it in GitHub Desktop.
JavaScript custom iterable
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
const countToThree = { | |
a: 1, | |
b: 2, | |
c: 3 | |
}; | |
countToThree[Symbol.iterator] = function* () { | |
const keys = Object.keys(this); | |
const length = keys.length; | |
for (const key in this) { | |
yield this[key]; | |
} | |
}; | |
let [...three] = countToThree; | |
console.log(three); // [ 1, 2, 3 ] |
What you're missing is that the [Symbol.iterator] we implemented was a generator function, which creates the iterable methods for you automatically.
As you can see if you try to run that code in a recent version of Node, it works just fine.
let [...three] = countToThree;
console.log(three); // [ 1, 2, 3 ]
for...of
also works:
for (i of countToThree) console.log(i);
// 1
// 2
// 3
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The MDN says that you can make your own iterators with just the Symbol, but you also need to implement the Iterable interface and the next() method as far as i know.
Link to spec: http://www.ecma-international.org/ecma-262/6.0/#sec-iterable-interface
I'm wrong?