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 === 2What it has to do
- Cache results based on serialized arguments.
- Do not re-execute
fnwhen 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.
Try it yourself· Edit the code, then press Run
Loading playground...
- 1.caches function result for same inputs
These assertions run in your browser the moment you hit Run. Pass all of them to claim the XP.
1 tests · +200 XP
Discussion
Sign in to postSign in to join the conversation.Sign in
No comments yet. Be the first to say something.