javascript
29 lines · 7 steps
Building a memoize wrapper in JavaScript
A higher-order function caches results by argument so expensive calls run only once per input.
Explained by
highlit
1function memoize(fn, resolver) {
2 const cache = new Map();
3
4 function memoized(...args) {
5 const key = resolver ? resolver(...args) : JSON.stringify(args);
6
7 if (cache.has(key)) {
8 return cache.get(key);
9 }
10
11 const result = fn.apply(this, args);
12 cache.set(key, result);
13 return result;
14 }
15
16 memoized.cache = cache;
17 memoized.clear = () => cache.clear();
18
19 return memoized;
20}
21
22const fibonacci = memoize(function fib(n) {
23 return n < 2 ? n : fibonacci(n - 1) + fibonacci(n - 2);
24});
25
26const distance = memoize(
27 (a, b) => Math.hypot(b.x - a.x, b.y - a.y),
28 (a, b) => `${a.x},${a.y}:${b.x},${b.y}`
29);
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1A closure over a Map lets each memoized function keep its own private, persistent cache.
- 2A custom resolver turns non-primitive arguments into reliable cache keys where JSON.stringify falls short.
- 3Attaching helpers like clear onto the returned function exposes control over the cache without leaking it.
Related explainers
javascript
function evaluate(expression) { const tokens = tokenize(expression); let pos = 0;
Building a recursive descent calculator
parsing
recursion
operator-precedence
Intermediate
8 steps
php
<?php namespace App\Services;
How a password strength validator works in PHP
validation
regular-expressions
data-driven
Intermediate
8 steps
javascript
import { useState, useEffect, useCallback, useRef } from 'react'; const cache = new Map(); const inflight = new Map();
Building a stale-while-revalidate hook in React
caching
request-deduplication
custom-hooks
Advanced
10 steps
php
<?php namespace App\Services;
Building a cached daily leaderboard in Laravel
caching
aggregation
eager-loading
Intermediate
9 steps
python
import secrets from django.contrib.auth import authenticate, login from django.core.cache import cache
Two-factor login with OTP in Django
two-factor-auth
one-time-passwords
caching
Intermediate
9 steps
javascript
import { useEffect, useRef, useState } from 'react'; export function useDelayedFlag(active, delay = 300) { const [visible, setVisible] = useState(false);
Delaying a loading spinner with a React hook
custom-hooks
debouncing
cleanup
Intermediate
8 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/building-a-memoize-wrapper-in-javascript-explained-javascript-9d1a/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.