[snip]
function(n) {
return (n in cache)
? cache[n]
: cache[n] = (function fibonacci (x) {
if(x < 2) return 1;
return fibonacci (x-1) + fibonacci(x-2);
})(n);
};
where cache has been defined in such a way as to be available when the
function is called. The following syntax means that the internal
function should have the value stored in "n" assigned to its parameter
"x":
(function internal(x) {
// return result of calculations involving x
})(n); // with the value of "n" assigned to "x"
Cheers,
-- Scott
I can make sense of it only by looking at it 2 ways. (1) the
way you describe it above -- and I am taking that quite a lot on
faith, since the n parameter is being passed not only to the
function it was sent to but by to the anonymous function which
is outside where the passed function is actually used.
(2) it semms fine to me that the function along with its parameter,
however named
is plopped in IN FULL as sent (with filled parameter) to the spot
where it is used (fully appreciating the name of the parameter
does not matter).
To reiterate:
Really, the only strange part of the situation is that the
outer anonymous function being returned using
the function that was sent has access to the parameter,
whatever it is called, and that is what you claim -- which
I again must take on faith just because it is what
you say with your code translation happens.
But I hate to take things
on faith and how that happens is still not clear.
So, it is still weird to me that in the following, the return function
(n) { ...}
the outer anon function is given THAT param. It is not strange that
the f(x) in the inner function can get f(x):
function memoize(f) {
var cache = {};
return function (n) {
return (n in cache)? cache[n] : cache[n] = f(n);
};
}
function fibonacci (x) {
if(x < 2) return 1; else return fibonacci (x-1) + fibonacci
(x-2);
}
fibonacci = memoize(fibonacci);
alert(fibonacci(5));