# ClosedRange

[JS](../../..)⟩ [iteration](../..) ⟩ [iterable](..) ⟩ [custom]() ⟩ ClosedRange

{% tabs %}
{% tab title="💾 程式" %}
:floppy\_disk: replit：[ClosedRange](https://replit.com/@pegasusroe/Range-iterable#index.js)

👉 compare： [closedrange](../../generator/examples/closedrange "mention") (the easy way), [list](../../generator/examples/list "mention")

```javascript
// ⭐ 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);
}
```

💈範例：

```javascript
// 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 ]
```
{% endtab %}

{% tab title="📗 參考" %}
* [ ] JavaScript: The Definitive Guide ⟩ 12.2 Implementing Iterable Objects
* [ ] JS.info ⟩ [iterables](https://javascript.info/iterable)
{% endtab %}

{% tab title="👥 相關" %}
* [make-iterables](../make-iterables "mention")
* [closedrange](../../generator/examples/closedrange "mention") - range of integers (generator: the easy way)
* [list](../../generator/examples/list "mention") - finite arithmetic sequence
* [integers](../../generator/examples/integers "mention") - infinite non-negative integers
{% endtab %}
{% endtabs %}
