Home > Web Front-end > JS Tutorial > body text

javascript uses memory function to quickly calculate recursive functions_javascript skills

WBOY
Release: 2016-05-16 18:32:30
Original
1222 people have browsed it

If there is a fibonacci sequence to be calculated:

Copy the code The code is as follows:

var fibonacci = function (n) {
return n < 2 ? n : fibonacci(n - 1) fibonacci(n - 2);
};

I am afraid that if the number is large, the browser will It crashed because the function would have a lot of repeated calculations during the operation. But JavaScript’s powerful arrays and function closures make it easy to memorize calculated results. The computing speed will increase exponentially.

Small but powerful memory function:
Copy code 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’s even easier to use:
Copy code The code is as follows:

var fibonacci = memoizer( [0, 1], function (shell, n) {
return shell(n - 1) shell(n - 2);
});

Similarly, if you want Calculate factorial sequence:
Copy code The code is as follows:

var factorial = memoizer([1, 1], function (shell, n) {
return n * shell(n - 1);
});
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template