It is taken from JavaScript: TheGoodParts and used as a backup for Reading Notes. For more information about efficiency, see. If there is a fibonacci series to be calculated:
The 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:
The 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:
The 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:
The Code is as follows:
Var factorial = memoizer ([1, 1], function (shell, n ){
Return n * shell (n-1 );
});