The shortest forms I came up with were:
Recursive function:
function f(n){return n<3?1:f(n-1)+f(n-2)}
In case I am using the direct return and applying a conditional operator to test if the value is less than 3 to return 1 and otherwise it applies the recursive calculation.
This way you can eliminate the comma, declaration of variables or very expressive syntaxes. But performance is one of the worst.
Cached function in variables:
function f(n,a,b){return n<3?1:!a?f(n-1)+f(n-2):!b?f(n-1)+a:a+b}
In this case I used the same conditional operator resource, but also includes a test to see if a
exists and then b
by changing the calculation formula to use the cache if it is available.
The same function can be written as follows:
function f(n,a,b){
if (n < 3) return 1;
if (typeof a === 'undefined') return f(n - 1) + f(n - 2);
if (typeof b === 'undefined') return f(n-1)+a;
return a+b;
}
Array Cache Function:
function f(n,c){c=c|[];return !c[n]?c[n]=n<3?1:f(n-1,c)+f(n-2,c):c[n]}
First I test using |
(bitwise operator or) to see if the c
variable that represents the cache exists, if it exists, I use it myself, if it does not, it receives a new array as value.
In the calculation, it will be checked if there is a cached value before anything, there is nothing in the cache, it will check if the value is less than 3 to return 1 or try to recursively apply the same function.
To get a better use of the cache you can adapt it in this way:
function f(n){return !f.c[n]?f.c[n]=n<3?1:f(n-1)+f(n-2):f.c[n]};f.c=[];
In this case the cache is being stored as a property of the function, and can be reused in the next few times when the function is executed, not having to re-calculate the values already added in the cache.
One way to better read this function would be:
function f(n) {
if (typeof f.cache[n] === 'undefined') {
if (n < 3) {
f.cache[n] = 1;
return f.cache[n];
}
f.cache[n] = f(n - 1) + f(n - 2)
return f.cache[n];
}
return f.cache[n];
}
f.cache=[];