If there is a fibonacci series to be calculated:
Copy codeThe Code is as follows:
Var maid = function (n ){
Return n <2? N: Maid (n-1) + maid (n-2 );
};
I am afraid that a large number of browsers will collapse, because there will be a large number of repeated computations in the operation process. However, JavaScript's powerful arrays and function closures allow you to easily remember the computed results. The computing speed will increase exponentially.
Small and powerful memory functions:
Copy codeThe Code is as follows:
Var memoizer = function (memo, fundamental ){
Var shell = function (n ){
Var result = memo [n];
If (typeof result! = 'Number '){
Result = fundamental (shell, n );
Memo [n] = result;
}
Return result;
};
Return shell;
};
The first parameter is the initial memory sequence, and the second parameter is the basic function. It is easier to use:
Copy codeThe Code is as follows:
Var fibonacci = memoizer ([0, 1], function (shell, n ){
Return shell (n-1) + shell (n-2 );
});
Similarly, if you want to calculate the factorial series:
Copy codeThe Code is as follows:
Var factorial = memoizer ([1, 1], function (shell, n ){
Return n * shell (n-1 );
});