If there is a fibonacci sequence to be calculated:
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:
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:
var fibonacci = memoizer( [0, 1], function (shell, n) {
return shell(n - 1) shell(n - 2);
});
Similarly, if you want Calculate factorial sequence:
var factorial = memoizer([1, 1], function (shell, n) {
return n * shell(n - 1);
});
Statement: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