JavaScript - Memoization

javascript

https://www.sitepoint.com/implementing-memoization-in-javascript/

See the above link for more details.

// JavaScript - Memoization:

var fibonacci = (function() {
  var memo = {};

  function f(n) {
    var value;

    if (n in memo) {
      value = memo[n];
    } else {
      if (n === 0 || n === 1)
        value = n;
      else
        value = f(n - 1) + f(n - 2);

      memo[n] = value;
    }

    return value;
  }

  return f;
})();

function cacheFn(fn) {
    var cache={};

    return function(arg){
        if (cache[arg]){
           return cache[arg];
        }
        else{
           cache[arg] = fn(arg);
            return cache[arg];
        }
    }
}

return function(){
  var args = arguments;  
  var key = [].slice.call(args).join('');
  if (cache[key]) {
      return cache[key];
  } else {
      cache[key] = fn.apply(thi, args);
      return cache[key];
  }
}
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License