Created
January 29, 2022 13:21
-
-
Save yuriitaran/d81a018c1fef4d125389dae698d4009a to your computer and use it in GitHub Desktop.
Simple iterator
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
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