Currying
intermediateTransform f(a, b, c) into f(a)(b)(c): the classic closure exercise, with arity handling.
Implement a memoize function in JavaScript that caches results by argument key, with cache-key strategy, Map vs object, and memory trade-offs.
The _.memoize method in Lodash is used to optimize functions by caching the results of function calls. When the memoized function is called with the same arguments, it returns the cached result instead of recalculating it.
Let’s implement a custom version of the _.memoize() function.
_.memoize()?The _.memoize() function is used to speed up the performance of functions by caching the results of expensive computations. When the function is called again with the same arguments, the cached result is returned, thus avoiding redundant calculations.
Interviewers might ask you to:
_.memoize.customMemoize FunctionHere’s how you can implement a custom memoize function:
function customMemoize(func, resolver) {
const cache = new Map();
return function(...args) {
const key = resolver ? resolver(...args) : args[0];
if (cache.has(key)) {
return cache.get(key);
}
const result = func.apply(this, args);
cache.set(key, result);
return result;
};
}Map to store the results of function calls. The Map object allows us to associate a specific key with a result, making it easy to check if a result for a given set of arguments already exists.resolver function allows customization of the cache key. If no resolver is provided, the first argument is used as the key by default.Let's see the customMemoize function in action:
// A simple function that returns the square of a number
const square = customMemoize((n) => {
console.log('Calculating square of', n);
return n * n;
});
console.log(square(4)); // Output: Calculating square of 4 \n 16
console.log(square(4)); // Output: 16 (cached result)
console.log(square(5)); // Output: Calculating square of 5 \n 25
// Using a custom resolver to memoize a function that takes multiple arguments
const add = customMemoize((a, b) => a + b, (a, b) => `${a}-${b}`);
console.log(add(1, 2)); // Output: 3
console.log(add(1, 2)); // Output: 3 (cached result)
console.log(add(2, 3)); // Output: 5_.memoize()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.