Skip to content

Instantly share code, notes, and snippets.

@dondevi
Last active February 12, 2018 10:15
Show Gist options
  • Save dondevi/dfe57d1c0ce4b78e82e07e14214b3161 to your computer and use it in GitHub Desktop.
Save dondevi/dfe57d1c0ce4b78e82e07e14214b3161 to your computer and use it in GitHub Desktop.
/**
* 斐波那契数列
* of ES6
*/
function fibonacci () {
let fn1 = 0;
let fn2 = 1;
let next = reset => {
if (reset) {
fn1 = 0;
fn2 = 1;
}
let current = fn1;
[fn1, fn2] = [fn2, fn1 + fn2];
return { value: current, done: false };
};
return { next };
}
/**
* 斐波那契数列
* of ES7
*/
function* fibonacci2 () {
let fn1 = 0;
let fn2 = 1;
while (true) {
let current = fn1;
[fn1, fn2] = [fn2, fn1 + fn2];
let reset = yield current;
if (reset) {
fn1 = 0;
fn2 = 1;
}
}
}
let f1 = fibonacci();
let f2 = fibonacci2();
console.log(f1.next(), f2.next());
console.log(f1.next(), f2.next());
console.log(f1.next(), f2.next());
console.log(f1.next(), f2.next());
console.log(f1.next(true), f2.next(true));
console.log(f1.next(), f2.next());
console.log(f1.next(), f2.next());
console.log(f1.next(), f2.next());
console.log(f1.next(), f2.next());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment