Skip to content

JavaScript迭代协议 #10

@clumsyme

Description

@clumsyme
// this is like __iter__ method in python
class MyIter {
    constructor(limit) {
        this.now = 0
        this.limit = limit
        this[Symbol.iterator] = () => ({
            next: () => {
                if (this.now < this.limit) {
                    this.now += 1
                    return { value: this.now**2, done: false }
                } else {
                    return { done: true }
                }
            }
        })
    }
}

let mi = new MyIter(5)

[...mi] // [1, 4, 9, 16, 25]

// Then again
[...mi] // []

let nmi = new MyIter(3)

for (let i of nmi) {
    console.log(i)
}
// 1
// 4
// 9

OR LIKE THIS

class MyIter {
    constructor(limit) {
        this.now = 0
        this.limit = limit
    }
    [Symbol.iterator]() {
        return {
            next: () => {
                if (this.now < this.limit) {
                    this.now += 1
                    return { value: this.now ** 2, done: false }
                } else {
                    return { done: true }
                }
            }
        }
    }
}

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions