当前位置: 移动技术网 > IT编程>开发语言>JavaScript > js设计模式之BehavioralPatterns之Iterator

js设计模式之BehavioralPatterns之Iterator

2018年06月12日  | 移动技术网IT编程  | 我要评论
class KingSuccession {
    constructor(inLineForThrone){
        this.inLineForThrone = inLineForThrone;
        this.pointer = 0;
    }
    next(){
        return this.inLineForThrone[this.pointer++];
    }
}
var kin = new KingSuccession(["Robert Baratheon","JofferyBaratheon","TommenBaratheon"]);
kin.next();
kin.next();
kin.next();

An interesting application of iterators is to not iterate over a fixed collection. For
instance an iterator can be used to generate sequential members of an infinite set
like the fibonacci sequence:

class FibonacciIterator{
    constructor(){
        this.previous = 1;
        this.beforePrevious = 1;
    }
    next(){
        var current = this.previous + this.beforePrevious;
        this.beforePrevious = this.previous;
        this.previous = current;
        return current;
    }
}
var fib = new FibonacciIterator();
fib.next();
fib.next();
fib.next();

Iterators are a syntactic nicety that has long been missing from Script. Another
great feature of ECMAScript-2015 are generators. This is, in effect, a built in iterator
factory. Our fibonacci sequence could be rewritten like the following:

function* FibonacciGenerator () {
    var previous = 1;
    var beforePrevious = 1;
    while (true){
        var current = previous + beforePrevious;
        beforePrevious = previous;
        previous = current;
        yield  current;
    }
}
var fibo = new FibonacciGenerator();
fibo.next().value;
fibo.next().value;
fibo.next().value;

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网