Skip to content

Instantly share code, notes, and snippets.

@jialinhuang00
Last active January 18, 2018 09:03
Show Gist options
  • Save jialinhuang00/6f94e4aaa5b1a078aacd1dcf2ab58c43 to your computer and use it in GitHub Desktop.
Save jialinhuang00/6f94e4aaa5b1a078aacd1dcf2ab58c43 to your computer and use it in GitHub Desktop.
function fibonacci(n) {
//0,1,1,2,3,5,8,13,21,34,55
var start = [0, 1];
var i, j, k, x;
for (i = 0, j = 1, k = 0; k < n; i = j, j = x, k++) {
x = i + j;
start.push(x);
}
return start[n];
}
fibonacci(10);
// ---------------------------------------
function fibMemo(index, cache) {
cache = cache || [];
if (cache[index]) return cache[index];
else {
if (index < 3) return 1;
else {
cache[index] = fibMemo(index - 1, cache) + fibMemo(index - 2, cache);
}
}
return cache[index];
}
fibMemo(7);
// it's adorable but it may be shutdown as n becoming bigger.
function fibonacci(n) {
return n < 1 ? 0
: n <= 2 ? 1
: fibonacci(n - 1) + fibonacci(n - 2);
}
// ---------------------------------------
// shutdown, too
function fibonacci2(index) {
if (index === 0) return 0;
if (index < 3 &&) return 1;
else return fibonacci2(index - 1) + fibonacci2(index - 2);
}
fibonacci2(3); //2
@jialinhuang00
Copy link
Author

if using Generator

function* fibonacci() {
  var fn1 = 0;
  var fn2 = 1;
  while (true) {  
    var current = fn1;
    fn1 = fn2;
    fn2 = current + fn1;
    var reset = yield current;
    if (reset) {
        fn1 = 0;
        fn2 = 1;
    }
  }
}

var sequence = fibonacci();
console.log(sequence.next().value);     // 0
console.log(sequence.next().value);     // 1
console.log(sequence.next().value);     // 1
console.log(sequence.next().value);     // 2
console.log(sequence.next().value);     // 3
console.log(sequence.next().value);     // 5
console.log(sequence.next().value);     // 8
console.log(sequence.next(true).value); // 0
console.log(sequence.next().value);     // 1
console.log(sequence.next().value);     // 1
console.log(sequence.next().value);     // 2

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment