Rory Perro
Rory Perro

Reputation: 451

underscore memoize from scratch

In studying underscore memoize, I do not understand the line: var argString = Array.prototype.join.call(arguments,"_");. I know that it is creating a string of the arguments, but how is that applicable here?

_.memoize = function(func) {
    var output  = {}; 
    return function(){
        var argString = Array.prototype.join.call(arguments,"_");       
        if (output[argString] === undefined){ 
            output[argString] = func.apply(this, arguments); 
        }
        return output[argString];
    };
};

Upvotes: 2

Views: 534

Answers (1)

Raja Sekar
Raja Sekar

Reputation: 2130

In the above code, Initially an object is created with name output.

Next, key for the object is created based on the arguments.

example: consider a function,

function x(a,b,c){
   // argument will be in an array form, but not an Array actually
   console.log(argument) // will give array like structure.
}

Now, using Array.prototype.join.call(arguments,"_"); generating dynamic key based on the arguments.

Next,

if (output[argString] === undefined){ 
        output[argString] = func.apply(this, arguments); 
       }

this will check, dynamically generated key is there or not in output object,

if it is there it will return the value without function call otherwise it will call the function and cache the key and value in output object.

Hope you understand the logic behind this.

Upvotes: 3

Related Questions