Javascript function. Don't understand how function inside self-function work -
would ask javascript function.
i don't understand below function, thought @ line 4 fib(n-1)
return 1
, latter fib(n-2)
return 0
, , both add 1.
may know why final result f(10);
55
, can't head around this.
anyone can explain me happening behind scene, please?
thanks! ;)
var f = function fib(n) { if (n === 0) return 0; if (n === 1) return 1; if (n > 1) return fib(n - 1) + fib(n - 2); // *2 }; f(10); // 55
like this. typical recursive function, 2 base cases , 1 recursive step.
remember if n
10, fib(n - 1)
fib(9)
, , on:
fib(10) = fib(9) + fib(8) = 34 + 21 = 55 fib(9) = fib(8) + fib(7) = 21 + 13 = 34 fib(8) = fib(7) + fib(6) = 13 + 8 = 21 fib(7) = fib(6) + fib(5) = 8 + 5 = 13 fib(6) = fib(5) + fib(4) = 5 + 3 = 8 fib(5) = fib(4) + fib(3) = 3 + 2 = 5 fib(4) = fib(3) + fib(2) = 2 + 1 = 3 fib(3) = fib(2) + fib(1) = 1 + 1 = 2 fib(2) = fib(1) + fib(0) = 1 + 0 = 1 fib(1) = 1 fib(0) = 0
side note: although example illustration of recursive functions, it's extremely inefficient way calculate fibonacci numbers. better approach use memoization eliminate bulk of inefficiency:
var fib = (function () { var cache = [0, 1]; return function fib(num) { if (!(num in cache)) { cache[num] = fib(num - 1) + fib(num - 2); } return cache[num]; }; })(); console.log(fib(10));
Comments
Post a Comment