Skip to content

Instantly share code, notes, and snippets.

@ericelliott
Last active July 23, 2018 23:29
Show Gist options
  • Save ericelliott/f62714425d4603c0101d49f87935e1bf to your computer and use it in GitHub Desktop.
Save ericelliott/f62714425d4603c0101d49f87935e1bf to your computer and use it in GitHub Desktop.
JavaScript custom iterable
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 ]
@felixsanz
Copy link

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?

@ericelliott
Copy link
Author

ericelliott commented May 21, 2016

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