# Memoize a function

Cache results by argument so each input is computed once.

Canonical: https://1loc.dev/function/memoize-a-function/
Version: 1.0.0
Runtime: JavaScript · Node.js 22 / modern browsers
Verification: Usage lines executed in Node.js 22 and headless Chromium; no external services
Updated: 2026-10-28

## Implementation

```javascript
function memoize(fn) {
  const cache = new Map();
  return arg => {
    if (!cache.has(arg)) cache.set(arg, fn(arg));
    return cache.get(arg);
  };
}
```

## Usage

```javascript
let calls = 0;
const isEven = memoize(n => (calls += 1, n % 2 === 0));
[isEven(3), isEven(3), isEven(3)]; // → [false, false, false]
calls; // → 1
const fibonacci = memoize(n => (n <= 2 ? 1 : fibonacci(n - 1) + fibonacci(n - 2)));
fibonacci(50); // → 12586269025
```

Lines marked → were executed in Node.js 22 and in headless Chromium, and each result was compared with the value shown. Lines marked e.g. are illustrative.

## Limits

- The original cached with cache[arg] || …, so falsy results (0, "", false) were recomputed on every call: three calls above would have run three times. A Map also keeps 1 and "1" apart.
- One argument, compared with SameValueZero: two equal-looking objects are different keys.
- The cache never shrinks. In a long-running server, bound it (an LRU) or key it by a finite set.

The function does not validate its arguments. Add checks where it receives untrusted input.

## Source and license

Original: https://github.com/phuocng/1loc/blob/14b481cf60dff1620ab1bb99a43b1f68068cdd9b/contents/memoize-a-function.mdx
Author: Nguyen Huu Phuoc and original contributors
Contributors: Kikobeats
Source commit: 14b481cf60dff1620ab1bb99a43b1f68068cdd9b
Copyright (c) 2020 phuoc-ng
License: MIT — https://1loc.dev/licenses/
Maintainer: Oveyon
Modifications: Caches in a Map with has(); the original recomputed falsy results on every call and merged 1 and "1". Documented as a reference with executed usage lines. Original MDX retained as inert source evidence.
