Iterator polyfill
yield = return
function* getFibonnacciSequence () {
let val1 = 0, val2 = 1, swap;
yield val1;
yield val2;
while (true) {
swap = val1 + val2;
val2 = swap;
val1 = val2;
yield swap;
}
}
function getFibonnacciSequence () {
var val1 = 0, val2 = 1, swap, state = 0;
return {
next: function () {
switch (state) {
case 0:
state = 1;
return {value: val1, done: false};
case 1:
state = 2;
return {value: val2, done: false};
default:
swap = val1 + val2;
val2 = swap;
val1 = val2;
return {value: swap, done: false};
}
}
};
}
var iterator = getFibonnacciSequence();
console.log(iterator.next().value); // 1
console.log(iterator.next().value); // 2
// Iterator
function createIterator (items) {
return {
next: function () {
var done = (i >= items.length)
, value = !done ? items[i++] : undefined;
return {value: value, done: done};
}
};
}
var iterator = createIterator([1, 2, 3]);
console.log(iterator.next()); // {value: 1, done: false}
console.log(iterator.next()); // {value: 2, done: false}
console.log(iterator.next()); // {value: 3, done: false}
console.log(iterator.next()); // {value: undefined, done: true}
// for all other calls
console.log(iterator.next()); // {value: undefined, done: true}
// Generator
function* createGenerator (items) {
for (var i = 0, i < items.length; i++) {
yield items[i];
}
}
var generator = createGenerator([1, 2, 3]);
console.log(generator.next()); // 1
console.log(generator.next()); // 2
console.log(generator.next()); // 3
Комментариев нет:
Отправить комментарий