欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

js设计模式之BehavioralPatterns之Iterator

程序员文章站 2022-10-19 13:46:59
class KingSuccession { constructor(inLineForThrone){ this.inLineForThrone...
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;