memoization - Explanation on "JavaScript - the Good Parts" example (section 4.15)? -


An explanation of the code piece is required from the beginning html

in JS, section 4.15:

 < Code> var memoizer = function (memo, original) {var shell = function (n) {var result = memo [n]; If (type result! == 'number') {result = original (shell, n); Memo [n] = results; } Return results; }; Return shell; }; Var fibonacci = memoizer ([0, 1], function (shell, n) {return shell (n -1) + shell (n -2);});  

Question : How do we calculate Fibonacci (15), and if this is a simple Fibonacci (15) call, how does it work in detail?

Thanks for the help.

According to the suggestion of comments of your questions, if you can not follow the explanation in the book Code in the debugger to get a good sense of what is happening. But I give you a brief overview of what is happening:

What is being demonstrated is 'memoisation' which is a general optimization technique used in functional programming. A function is considered pure if the result depends only on the arguments passed on it. Therefore, if a function is pure then you can cache the results based on logic - this technique is called a memo, you can do it if calculating the function is expensive and sometimes called.

The classical examples being used (as it is here) are being produced. I am not going to go out of them how they are working, but basically when you go to higher and higher numbers, you repeat yourself again because each number is calculated from the first two numbers Is performed. By remembering each intermediate result, you need to calculate them once, so make the algorithm very fast (too much, the faster you go up the sequence, the faster).

As far as this code is concerned, parameter - 'memorandum' is the cache which is In this case this 'first [0,1]' is already running with the first two values ​​- these are the first two Fibonacci numbers.

The second parameter is the application for which the memoration will be applied. In this case, a recursive fibbon function:

function (shell, n) {return shell (n -1) + shell (n -2); }

i.e. The result is the sum of the last two digits in the sequence.

Before the investigator to see the investigator whether it already has a cached result, if it does, then it comes back immediately. If not, it calculates the result and stores it in the cache. Without doing so, it was repeated repeatedly and gradually becomes slower once to get higher number.


Comments