Iterator pattern applied rx

 

 

Iterator: a special object that contains a next method, the next method returns an object that contains two properties, is a value, a value indicating member, one is done, a boolean value is done type, it indicates the iteration whether the end.

 

 

 Method 1: Create an iterator-based es6 Manual:

const obj = {a: 'a', b: 'b', c: 'c'}

obj[Symbol.iterator] = function() {
    const self = this
    const keys = Object.keys(self)
    const len = keys.length
    let pointer = 0
    return {
        next() {
            const done = pointer >= len
            const value = !done ? self[keys[pointer++]] : undefined
            return {
                value,
                done
            }
        }
    }
}

 

Method 2: Based es6 generator (Generator): call creates an iterator object.

let creatiterators=function *(a) {

    if(a==1){

        yield "over"
    }else{
        a=1
        yield a+2;

        yield a+4

        yield {a:a}

    }
}

let liststream=creatiterators()


for (const val of liststream) {
    console.log(val)
}

  

Guess you like

Origin www.cnblogs.com/breakdown/p/12161636.html