ClosedRange

JSiterationiterablecustom ⟩ 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 ]

Last updated