Matthew Harwood Matthew Harwood - 13 days ago 9
Javascript Question

Can a memoize function use a ES6 Map vs a hashtable?

Preface: Trying to learn ES6 Maps through converting a simple memoize that leverages a hash table instead.

Question:



Can the starting Object be replaced with a
new Map()
, if so, how? And are there any advantages? if not, why?





Description:

Here's a memoize that takes function (
add
) and a starting object(
{}
). On call of the memoized add (
mAdd
) the parameters are spread. Finally, the hash index is tested/sets and value is returned.

LINK TO CODE





const memo = (fn, hash) => (...a) => {
return hash[a] === void 0 ? hash[a] = fn(...a) : `${hash[a]} memo`;
};

const add = (x, y) => x + y;

const mAdd = memo(add, {});


console.log(mAdd(2,2));
console.log(mAdd(2,2));





Not working with maps:



const memo = (fn, map) => (...a) => {
return map.get(a) === void 0 ? map.set(a, fn(...a)) : `${map.get(a)} memo`;
};

const add = (x, y) => x + y;

const mAdd = memo(add, new Map());


console.log(mAdd(2,2));
console.log(mAdd(2,2));




Answer

As far as I know Objects can't be used as key in Map. Have a look here Javascript HashTable use Object key

const memo = (fn, hash) => (...a) => {
  const key = JSON.stringify(a);
  if (hash.has(key)) {
    return `${hash.get(key)} memo`;        
  }
  const val = fn(...a);
  hash.set(key, val);
  return val;
};

const add = (x, y) =>  x + y;

const mAdd = memo(add, new Map());


console.log(mAdd(2,2));
console.log(mAdd(2,2));

Note: your code is not readable at all. So I had to edit it a bit to make it more understandable.