2 ms·
Because it's an awesome and easy way to create iterables. class FreakyCollection { [Symbol.iterator]() { return function*() { for /
by scotty79 4y ago
Because it's an awesome and easy way to create iterables.
class FreakyCollection {
[Symbol.iterator]() {
return function*() {
for //...
// iterate over your freaky collection however you please yielding one element by one
}();
}
- jitl 4y agoThis can be condensed slightly, you don't need the inner function literal. In Typescript: class MyCollection<T> { *[Symbol.iterator](): IterableIterator<MyCollectionEntry<T>> { for (const thingy of this.thingies) { yield { ... } } } }
- scotty79 4y ago... also custom and paremetrized iterators: class FreakyCollection { // ... *even() { // for ... iterate skipping the odd ones and yielding the rest one by one } *having(quality) { // for ... iterate and yield just the items that have some quality } and usage then is as simple as: for(let item of freakyCollection.having(42)) {