Home
← All questions

Memoize II: Multiple Arguments in JavaScript

MediumPremiumJavaScript

Asked at Rippling · Forward Networks · LinkedIn

Implement JavaScript memoization for multiple primitive arguments. Preserve argument order and types, avoid cache key collisions, and handle zero-argument calls.

Problem

Implement memoize(fn) for a function receiving any number of primitive arguments, including zero. Repeated calls with the same ordered argument tuple must reuse the result. Build on Memoize I by treating argument order, types, and argument count as part of the cache key.

Requirements

  • (1, 2) differs from (2, 1) and from ("1", 2).
  • () differs from (undefined), and (1) differs from (1, undefined).
  • Strings may contain separators such as "|"; joining arguments into a string must not create collisions.
  • Object and function arguments are outside this version.
  • Cache every returned value, including undefined, null, false, 0, and empty strings.
  • Each wrapper has its own cache. Exceptions are not cached.
  • Forward the caller's this when computing a result. Assume results depend only on the arguments; caching across different receivers is outside this problem.
  • Compare primitive keys using Map equality: NaN matches NaN, and 0 matches -0.
  • The function is synchronous and deterministic. Cache eviction and async rejection handling are follow-ups.

Example

let calls = 0;
const add = memoize((...nums) => { calls++; return nums.reduce((a, b) => a + b, 0); });
add(1, 2); // 3, computed
add(1, 2); // 3, cached
add(2, 1); // 3, computed: different order
add();     // 0, computed
add();     // 0, cached
console.log(calls); // 3

Starter code

function memoize(fn) {
  // Your code here
}

Related memoization interview questions

Premium question

Unlock the in-browser editor, test cases, and model solution with Mentoxis Premium.

Unlock with Premium