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
const express = require('express'); const router = express.Router(); const { pool } = require('../db'); const redis = require('../redis');
Building a health check endpoint in Express
health-check
timeouts
promise-race
Intermediate
9 steps
php
<?php namespace App\Http\Middleware;
Idempotent requests with Laravel middleware
idempotency
middleware
caching
Advanced
8 steps
javascript
'use client'; import { useEffect } from 'react'; import * as Sentry from '@sentry/nextjs';
How a Next.js error boundary recovers
error-boundary
error-handling
observability
Intermediate
8 steps
python
from django.contrib.postgres.search import SearchQuery, SearchRank, SearchVector from django.core.cache import cache from django.db.models import F from django.http import JsonResponse
Ranked full-text search in Django
full-text-search
debouncing
caching
Advanced
9 steps
typescript
type ResizeCallback = (size: { width: number; height: number }) => void; export function observeResize(callback: ResizeCallback, delay = 150) { let timeoutId: ReturnType<typeof setTimeout> | undefined;
Debouncing window resize in TypeScript
debounce
closures
event-listeners
Intermediate
6 steps
javascript
const MAX_BATCH_SIZE = 20; const FLUSH_INTERVAL = 5000; const ENDPOINT = '/api/analytics';
Batching analytics events in the browser
batching
buffering
sendbeacon
Intermediate
10 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.