WinchenzoMagnifico
WinchenzoMagnifico

Reputation: 3425

Trouble understanding memoize implementation

How does answerKey[parameters] work? if Array.prototype.slice.call(arguments) returns an array [157, 687], is answerKey[parameters] storing an array as key?

function memoize(mathProblem) {
  var answerKey = {};

  return function(){
    var parameters = Array.prototype.slice.call(arguments);

    if (answerKey[parameters]) {
      console.log('returning cached');
      return answerKey[parameters];
    } else {
      answerKey[parameters] = mathProblem.apply(this, arguments);

      return answerKey[parameters]
    }
  }
};

var multiply = function(a, b){
    return a*b;
}

var memoMultiply = memoize(multiply);

console.log(memoMultiply(157, 687));
=>
107859

console.log(memoMultiply(157, 687))
=>
returning cached
107859

Upvotes: 1

Views: 98

Answers (1)

t3dodson
t3dodson

Reputation: 4007

The square bracket notation will convert an array into a string

var answerKey = {};
var params = [157, 687];
answerKey[params] = 107859;
answerKey['157,687']; // 107859

So yes, the key is the content of the array as a string. This is not great practice.

EDIT REQUESTED

In general I try to avoid depending on strings that are created from Array.prototype.toString() because it has some odd behavior

for example. Nested arrays are flattened

[2, [3, 4], 5].toString(); // '2,3,4,5'

This is losing information about the source array and is indistinguishable from

[2, 3, 4, 5].toString();

To get around issues like these I suggest passing the array through JSON.stringify();

JSON.stringify([2, [3, 4], 5]); // '[2,[3,4],5]'
JSON.stringify([2, 3, 4, 5]); // '[2,3,4,5]'

This example will work with .toString(); but I think its a bad habit.

Upvotes: 4

Related Questions