Skip to content

Instantly share code, notes, and snippets.

@yuriitaran
Created January 29, 2022 13:21
Show Gist options
  • Save yuriitaran/d81a018c1fef4d125389dae698d4009a to your computer and use it in GitHub Desktop.
Save yuriitaran/d81a018c1fef4d125389dae698d4009a to your computer and use it in GitHub Desktop.
Simple iterator
const myObject = {
a: 2,
b: 3,
};
Object.defineProperty(myObject, Symbol.iterator, {
enumerable: false,
writable: false,
configurable: true,
value: function () {
const obj = this;
let idx = 0;
const ks = Object.keys(obj);
return {
next: function () {
return {
value: obj[ks[idx++]],
done: idx > ks.length,
};
},
};
},
});
// iterate `myObject` using iterator directly
const it = myObject[Symbol.iterator]();
console.log(it.next()); // { value:2, done:false }
console.log(it.next()); // { value:3, done:false }
console.log(it.next()); // { value:undefined, done:true }
// iterate `myObject` using `for..of`
for (const v of myObject) {
console.log(v);
}
// 2
// 3
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment