自定义iterator

229 阅读1分钟

1.定义iterator

 class Iterator  {
    constructor(arr) {
        this._arr = arr;
        this._cursor = -1;
        this.max = arr.length;
        this.min = -1;
    }
    next() {
        this._cursor = Math.min(this.max, this._cursor += 1)
        return {
            value: this._arr[this._cursor], 
            done: this._cursor >= this._arr.length
        }
    }
    prev() {
        this._cursor = Math.max(this.min, this._cursor -= 1)
        return {
            value: this._arr[this._cursor], 
            done: this._cursor < 0
        }
    }
 }

2.使用

    var ite = new Iterator([1,2,3]);
    ite.next(); //{value: 1, done: false}
    ite.next(); //{value: 2, done: false}
    ite.prev(); //{value: 1, done: false}
    ite.next();
    ite.next(); //{value: 3, done: false}
    ite.prev(); //{value: 2, done: false}
    ite.next();
    ite.next(); //{value: undefined, done: true}