DEV Community

Discussion on: Easiest way to convert JavaScript object to map!

Collapse
 
calag4n profile image
calag4n

Do you know some use cases in which functions as keys of a Map would be relevant ?

Collapse
 
hasnaindev profile image
Muhammad Hasnain • Edited

Doing that is less useful compared to passing objects as keys but not useless. Here is the best example I could come up with.

const map = new Map();

function computeOrGetValueFromCache(callback) {
  if (map.has(callback)) return map.get(callback);
  const value = callback();
  map.set(callback, value);
  return value;
}

const processedThumbnail = computeOrGetValueFromCache(processImage(thumbnail));
Enter fullscreen mode Exit fullscreen mode

Here we just implemented a caching system where a function that does some heavy computation runs only once and we don't have to worry about giving them clever and unique keys.

Also, keep in mind that in JavaScript, functions are objects! You can even use Function constructor to instantiate functions. Probably, that's why you can pass functions as keys to Map.

Collapse
 
calag4n profile image
calag4n

Oh, ok I got it .
Thanks for the example, it's helpful. 👍