I have a different approach to a similar problem:

{{{
function fib(n) {
  fib = function (n) {
    fib.calls++;
    if (fib.cache[n] === undefined) {
      fib.cache[n] = fib(n - 1) + fib(n - 2);
    }
    return fib.cache[n];
  }
  fib.calls = 0;
  fib.cache = [0, 1];
  return fib(n);
}

function reset(fn, cache) {
  fn.calls = 0;
  if (cache !== undefined) {
    fn.cache = cache;
  }
}

console.log("result of calling fib(10):", fib(10));
console.log('total calls:', fib.calls);
reset(fib);
console.log("result of calling fib(20):", fib(20));
console.log('total calls:', fib.calls);
reset(fib);
console.log("result of calling fib(10):", fib(10));
console.log('total calls:', fib.calls);
reset(fib);
console.log((new Array(20)).join('-'));
reset(fib, [0, 1]);
console.log("result of calling fib(10):", fib(10));
console.log('total calls after cache reset:', fib.calls);
reset(fib, [0, 1]);
console.log("result of calling fib(20):", fib(20));
console.log('total calls after cache reset:', fib.calls);
console.log((new Array(40)).join('-'));
}}}

The output is:
{{{
result of calling fib(10): 55
total calls: 19
result of calling fib(20): 6765
total calls: 21
result of calling fib(10): 55
total calls: 1
-------------------
result of calling fib(10): 55
total calls after cache reset: 19
result of calling fib(20): 6765
total calls after cache reset: 39
---------------------------------------
}}}

I dont know how do you like this approach, but it is what is kindof
the closest thing to JavaScript.

--
Poetro

-- 
To view archived discussions from the original JSMentors Mailman list: 
http://www.mail-archive.com/[email protected]/

To search via a non-Google archive, visit here: 
http://www.mail-archive.com/[email protected]/

To unsubscribe from this group, send email to
[email protected]

Reply via email to