Skip to content

Instantly share code, notes, and snippets.

@singhArmani
Created March 21, 2019 03:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save singhArmani/e51663f3461a291114176d4391cb7f3d to your computer and use it in GitHub Desktop.
Save singhArmani/e51663f3461a291114176d4391cb7f3d to your computer and use it in GitHub Desktop.
var obj = { x: 1, y: 2, z: 3 };
obj[Symbol.iterator] = function() {
// An iterator is an object which has a next method,
// which also returns an object with atleast one of two properties: value & done.
// returning an iterator object
return {
next: function() {
if (this._countDown === 3) {
const lastValue = this._countDown;
return { value: this._countDown, done: true };
}
this._countDown = this._countDown + 1;
return { value: this._countDown, done: false };
},
_countDown: 0
};
};
[...obj]; // will print [1, 2, 3]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment