The Ashes

Technology, Science and other news
May 10, 2009

A Better Javascript Memoizer

Posted by : admin
Filed under : General

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:

PLAIN TEXT
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 😉
Tags :

No Comments

(required)
(will not be published) (required)
(opitional)

cciash.com EN ES IT DE PT CZ FR RU
June 2018
M T W T F S S
« Sep    
 123
45678910
11121314151617
18192021222324
252627282930  

Pages

Categories

Resources

There are many online poker site where you can play but at poker.hk you can play the poker games with all the knowledge you need related to the game with the poker school available in both the English and Chinese language.

Super Casino

Now you can bet on any sports and any sporting events from all the comfort from your home. Bet770 allows you to bet on any events and match with in just 3 clicks. They also offers great odds on football betting for every premier and champions league match. Get £50 free in bets when you register.

Bingo770, offering best online bingo games with £7.70 free no deposit Bonus!