HomeAbout

Memoization

Simple memoization in JavaScript

function memoize(fn) { const cache = new Map(); // Initialize a new Map object for caching return function (n) { if (cache.has(n)) { // Check if result is already in cache return cache.get(n); } else { // Compute the result and store it in cache const result = fn(n); cache.set(n, result); return result; } }; }

Async Memoization in JavaScript

Function expects a passing of async_method.

  • Any async function that will take an argument.

cache variable is a cache recording registry.

  • Each record consists of key that is a stringified version of arguments passed to the method.
  • value that is a Promise (not yet awaited) that calls the async function with the given arguments.

We are caching the promise returned by the method, not the final value.

function memoize(async_method) { const cache = {}; return async function() { let args = JSON.stringify(arguments); // store promise (before awaiting) as value cache[args] = cache[args] || async_method.apply(this, arguments); return cache[args]; }; }

How to use it:

const getSomeDataMemoized = memoize(async function() { return await fetch("/api/someRoute", { method: "GET", }); }); const getAnotherRequestMemoized = memoize(async function() { return await fetch("/api/otherRequest", { method: "GET", }); }); const materFunction = memoize(async function() { const [result1, result2] = await Promise.all([ getSomeDataMemoized(), getAnotherRequestMemoized() ]); return result1; });
AboutContact