cialis online levitra generic viagra

A Better Javascript Memoizer

Written by on May 5th, 2009 in Uncategorized.

We have covered memoizers in the past, but John Hann has posted on a nice implementation that takes advantage of closures, arity, and recursion — 3 concepts/features that Javascript was meant to use.

It leads to this generic version:

JAVASCRIPT:

  1.  
  2. // memoize: a general-purpose function to enable a function to use memoization
  3. //   func: the function to be memoized
  4. //   context: the context for the memoized function to execute within
  5. //   Note: the function must use explicit, string-serializable parameters
  6. function memoize (func, context) {
  7.     function memoizeArg (argPos) {
  8.         var cache = {};
  9.         return function () {
  10.             if (argPos == 0) {
  11.                 if (!(arguments[argPos] in cache)) {
  12.                     cache[arguments[argPos]] = func.apply(context, arguments);
  13.                 }
  14.                 return cache[arguments[argPos]];
  15.             }
  16.             else {
  17.                 if (!(arguments[argPos] in cache)) {
  18.                     cache[arguments[argPos]] = memoizeArg(argPos - 1);
  19.                 }
  20.                 return cache[arguments[argPos]].apply(this, arguments);
  21.             }
  22.         }
  23.     }
  24.     // JScript doesn’t grok the arity property, but uses length instead
  25.     var arity = func.arity || func.length;
  26.     return memoizeArg(arity - 1);
  27. }
  28.  

and this conclusion:

Yes, memoization is a neat concept. But why use it rather than just hand-coded caching mechanisms? It’s easy enough to write a caching routine, right? Here are a few good reasons:

  • hand-coded caching mechanisms obfuscate your code
  • multi-variate caching routines are bulky in Javascript
  • fewer lines of code means fewer bugs
  • Java programmers will think more highly of you ;)

Source: Ajaxian » Front Page
Original Article: http://feedproxy.google.com/~r/ajaxian/~3/LaHnGeRfmqQ/a-better-javascript-memoizer

Comments are closed.



Site Navigation