The next feature suggested by "Doug Crockford: JavaScript: Good Details." works great.
var fibonacci = function () { var memo = [0, 1]; var fib = function (c) { console.debug(memo, c, memo[c]); result = memo[c]; if (typeof result !== 'number'){ result = fib(c - 1) + fib(c - 2); memo[c] = result; } return result; }; return fib; }(); console.log(fibonacci(3));
But let's take a closer look at what happens with line 4
console.debug(memo, c, memo[c]);
He shows the following result, which is the opposite of what was expected.
memo, c, memo[c] [0, 1, 1, 2] 3 undefined //contradictory behavior because I expect to have memo = [0, 1] [0, 1, 1, 2] 2 undefined //contradictory behavior [0, 1, 1, 2] 1 1 [0, 1, 1, 2] 0 0 [0, 1, 1, 2] 1 1 2
Some ideas?
source share