โจClosedRange
Last updated
Last updated
JSโฉ iteration โฉ iterable โฉ custom โฉ ClosedRange
replit๏ผClosedRange
๐ compare๏ผ *closedRange() (the easy way), *list()
// โญ closed range of integers
// (an iterable, which can make iterators)
class ClosedRange {
// init
constructor(start, end) {
this.start = start;
this.end = end;
}
// โญ "make iterator" method
// return an "iterator object" directly
[Symbol.iterator]() {
// private variables (in a closure) that can be accessed
// by the returned iterator
let current = this.start;
const { end } = this;
// โญ return the iterator
return {
// โญ an iterator must have the `next()` method
next() {
// โญ `next()` method must return an iteration result object.
return (
(current <= end) ? { value: current++ } : { done: true }
)
},
// make this iterator iterable for convenience
[Symbol.iterator]() { return this },
}
}
}
// convenience function
function closedRange(start, end) {
return new ClosedRange(start, end);
}
๐็ฏไพ๏ผ
// for-of loop
for (const i of closedRange(1, 3)) console.log(i); // 1 2 3
// spread into array elements
[...closedRange(1, 5)] // [ 1, 2, 3, 4, 5 ]
*closedRange() - range of integers (generator: the easy way)
*list() - finite arithmetic sequence
*integers() - infinite non-negative integers