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
thiswhen computing a result. Assume results depend only on the arguments; caching across different receivers is outside this problem. - Compare primitive keys using
Mapequality:NaNmatchesNaN, and0matches-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
}