Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

Map is really handy for writing memoization-type functions:

  const memoize = func => {
    const cache = new Map();

    const memoized = arg => {
      const cached = cache.get(arg);

      if (cached !== undefined) {
        return cached;
      }

      const result = func(arg);
      cache.set(arg, result);

      return result;
    };

    memoized.clearCache = cache.clear.bind(cache);

    return memoized;
  };
(Also, you could use WeakMap instead of Map if you knew the memoized function would only ever receive objects as arguments.)


Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: