Cache function results to avoid redundant calculations and improve performance for expensive operations.
Code
Boilerplatesconst memoize = (fn) => {
const cache = new Map();
return (...args) => {
const key = JSON.stringify(args);
if (cache.has(key)) return cache.get(key);
const result = fn(...args);
cache.set(key, result);
return result;
};
};
const fib = memoize(n => n <= 1 ? n : fib(n - 1) + fib(n - 2));
return fib(10);Browser·fetch() may be limited by CORS
More JavaScript Snippets
Debounce
Create a debounced function that delays execution until after a specified wait period has elapsed since the last call.
Once
Create a function that can only be called once, returning the cached result for subsequent invocations.
Parallel with Limit
Run promises in parallel with a concurrency limit to control resource usage and prevent overwhelming external services.
Promise.allSettled
Wait for all promises to settle, whether they resolve or reject.
Promise.any
Return the result of the first promise that resolves successfully.
Retry with Backoff
Retry an async function with exponential backoff to handle transient failures gracefully.