<!--
title: Encapsulate Memoization Cache
domain: app-frameworks
topic: Caching
language: Markdown
source: 30-seconds/30-seconds-of-code
updated: 2018-01-02
url: https://awesomereviewers.com/reviewers/30-seconds-of-code-encapsulate-memoization-cache/
-->

When implementing in-memory caching (e.g., memoization), use a `Map` for the cache and keep the cache implementation private.

- Use `Map` instead of plain objects to avoid prototype/key pitfalls and to support non-string keys safely.
- Do not expose the cache object (e.g., via `returnedFn.cache = cache`). External reads/writes can corrupt cached state and cause unpredictable results.

Example (safe memoize):
```js
const memoize = fn => {
  const cache = new Map(); // private
  return value => {
    if (cache.has(value)) return cache.get(value);
    const result = fn(value);
    cache.set(value, result);
    return result;
  };
};
```
