Can anyone explain what is happening in the code below that is using JS and memoization technique

Viewed 661

It'd be very helpful if someone can explain what is happening here step by step in a simple manner. I know memoize() is caching the functions but I need a better understanding. Thank you!

var memoize = function (f) {
  var cache = {};
  return function () {
    var str = JSON.stringify(arguments);
    cache[str] = cache[str] || f.apply(f, arguments);
    return cache[str];
  };
};

var mUser = memoize(function(x){
  return function() {
    return x;
  };
});

var x = mUser(1);
var y = mUser(2);
console.log(x());  //1
console.log(y());  //2

Edit : I'm keeping the original for record. But posting modified code and my understanding of it. I need opinions if I'm right or wrong and some explanation for either.

var memoize = function (injected) {
  var cache = {};
  return function closure_with_access_to_cache () {
    var str = JSON.stringify(arguments);
    cache[str] = cache[str] || injected.apply(injected, arguments);
    console.log(cache);
    return cache[str];
  };
};

var memoizeUser = memoize (function injected(a) {
  return function closure_with_access_to_a () {
    return a;
  };
});

memoizeUser();

Let's try to backtrack things.

First thing is, when memoizeUser(); statement is getting executed, what is represented by memoizeUser or which function is getting called first ?

var memoizeUser = ... is a function expression, means it is not getting hoisted.

So, memoize is called.

But, var memoize = ... is a function expression too. Looking at it carefully, it is a closure closure_with_access_to_cache and receiving the param passed to memoizeUser when it is called.

Inside this closure_with_access_to_cache, first time, cache is empty so injected.apply(injected, arguments) is executed and got another closure closure_with_access_to_a as returned value. This value is stored to cache and then returned. So, memoizeUser actually becomes closure_with_access_to_a with a equal to the value passed to memoizeUser.

Let's look at some calls and logs.

console.log(memoizeUser());
{ '{}': [Function: closure_with_access_to_a] }
[Function: closure_with_access_to_a]

Cache key is empty object because nothing was passed as param to memoizeUser(). memoizeUser() returns function closure_with_access_to_a which is logged.

console.log(memoizeUser()());
{ '{}': [Function: closure_with_access_to_a] }
undefined

memoizeUser() returns function closure_with_access_to_a which is called and logged undefined which was the value of a as nothing was passed to memoizeUser.

memoizeUser(1);
{ '{"0":1}': [Function: closure_with_access_to_a] }

Like above except a had value of 1.

console.log(memoizeUser(1)());
{ '{"0":1}': [Function: closure_with_access_to_a] }
1

Like above except a had value of 1.

2 Answers
Related