js设计模式----Behavioral Patterns之Iterator(4)
程序员文章站
2024-02-20 20:20:17
...
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 JavaScript. 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;
上一篇: js中的类
下一篇: ibatis之iterator研究