AniUI Academy

Function Memoization Cache

mediumFunctions & Closures+200 XPFrontend AlgoArena

Memoization trades memory for time: cache a function's result the first time it runs with a given set of arguments, and return the cached value on subsequent calls. Pure functions are the natural fit — the same inputs always yield the same output.

Implement memoize(fn) returning a wrapper that calls fn once per unique argument tuple. Design the cache key so that memoized(1, 2) and memoized(2, 1) are treated as different inputs.

Arguments

fnFunction
A pure function whose return value should be cached.

Returns

Function — A memoized version of fn.

Examples

let executions = 0;
const add = memoize((a, b) => { executions++; return a + b; });

add(2, 3); // runs — returns 5, executions === 1
add(2, 3); // cache hit — returns 5, executions still 1
add(1, 4); // different args — runs, executions === 2

What it has to do

  • Cache results based on serialized arguments.
  • Do not re-execute fn when called with identical arguments.

Notes

  • JSON.stringify(args) is a serviceable key for primitives. If arguments can be objects, remember that two structurally-identical objects stringify the same but are different references — that may or may not be what you want.
Asked atMetaGoogleMicrosoft
Try it yourself
Loading playground...
1 tests · +200 XP

Discussion

Sign in to post
Sign in to join the conversation.Sign in

No comments yet. Be the first to say something.