Currying
intermediateTransform f(a, b, c) into f(a)(b)(c): the classic closure exercise, with arity handling.
Implement memoizeLast in JavaScript — a single-slot memoizer that remembers only the previous call, the same pattern React's useMemo uses.
The memoizeLast() method is a variation of memoization that specifically caches the result of the most recent function call. Unlike traditional memoization, which might cache results for multiple sets of arguments, memoizeLast() only remembers the last set of arguments and the corresponding result. This is useful for functions that are often called with the same arguments consecutively.
Let’s implement a custom memoizeLast() function in JavaScript.
memoizeLast()?The memoizeLast() function is a performance optimization technique that caches the result of the last function call. When the function is called again with the same arguments, it returns the cached result instead of recomputing it. If the function is called with different arguments, the cache is updated with the new result.
Interviewers might ask you to:
customMemoizeLast FunctionHere’s how you can implement a custom memoizeLast function:
function customMemoizeLast(func) {
let lastArgs = null;
let lastResult = null;
return function(...args) {
if (lastArgs && lastArgs.length === args.length && lastArgs.every((arg, index) => arg === args[index])) {
return lastResult;
}
lastResult = func.apply(this, args);
lastArgs = args;
return lastResult;
};
}lastArgs and the corresponding result in lastResult.Let's see the customMemoizeLast function in action:
// A simple function that adds two numbers
const add = customMemoizeLast((a, b) => {
console.log('Calculating:', a, '+', b);
return a + b;
});
console.log(add(2, 3)); // Output: Calculating: 2 + 3 \n 5
console.log(add(2, 3)); // Output: 5 (cached result)
console.log(add(3, 4)); // Output: Calculating: 3 + 4 \n 7
console.log(add(3, 4)); // Output: 7 (cached result)
// Handling functions with more complex arguments
const complexAdd = customMemoizeLast((obj1, obj2) => {
console.log('Calculating:', obj1, '+', obj2);
return obj1.value + obj2.value;
});
console.log(complexAdd({ value: 10 }, { value: 20 })); // Output: Calculating: {value: 10} + {value: 20} \n 30
console.log(complexAdd({ value: 10 }, { value: 20 })); // Output: 30 (cache miss because objects are not strictly equal)===) for arguments. If deep comparison is needed, this logic must be adjusted.memoizeLast()Transform f(a, b, c) into f(a)(b)(c): the classic closure exercise, with arity handling.
The harder follow-up: support _ placeholders so arguments can arrive in any order.
Compose functions left-to-right into a pipeline — the one-liner with a lot of interview depth.
Pre-fill leading arguments of a function — partial application, and how it differs from currying.