Course contentsShow
← JavaScript
Lesson 2376 of 2,72349. Common Patterns and IdiomsFree lesson

Handling Multiple Arguments

Memoizing functions with multiple parameters using argument serialization.

Handling Multiple Arguments

What You'll Learn

You'll learn how to memoize functions that accept multiple parameters by serializing their arguments into a single cache key.


The Challenge with Multiple Parameters

The basic memoization pattern you've learned works beautifully for single-argument functions—just use the argument itself as the cache key. But what happens when your expensive function takes multiple arguments?

function expensiveCalculation(a, b, c) {
  console.log('Computing...');
  return a * b + c;
}

If you try cache[a] = result, you're ignoring b and c entirely—you'll get wrong results!


Argument Serialization

The solution is serializing (converting) all arguments into a single string that uniquely represents that combination of inputs. The simplest approach is to join arguments with a delimiter:

function memoize(fn) {
  const cache = {};
  return function(...args) {
    const key = args.join('|'); // Serialize arguments
    if (key in cache) {
      return cache[key];
    }
    const result = fn(...args);
    cache[key] = result;
    return result;
  };
}

const memoized = memoize(expensiveCalculation);
memoized(2, 3, 4);  // "Computing..." → 10
memoized(2, 3, 4);  // (cached) → 10
memoized(2, 4, 3);  // "Computing..." → 11 (different key!)

The key "2|3|4" uniquely identifies this specific combination of arguments.


Why This Works

Think of it like a filing system: instead of one drawer per argument, you create a single label that captures all the information needed to identify that exact calculation.


Key Takeaway:
Memoizing multi-argument functions requires serializing all arguments into a single, unique cache key—commonly done by joining them into a delimited string.