Memoization and Currying with Closures
1. Memoization with Closures
Memoization is a technique to optimize performance by caching the results of expensive function calls. The memoize
function uses a closure to store a cache object that maps arguments to results. This reduces redundant computations, especially in recursive functions like fibonacci
.
2. Function Currying with Closures
Currying transforms a function with multiple arguments into a sequence of functions, each taking a single argument. The curry
function creates a closure that accumulates arguments until all required arguments are provided. This enables partial application of functions.
Here’s the combined code snippet, including both memoize
and curry
utilities:
js
1 // Memoization Utility2 function memoize(fn) {3 const cache = {};45 return function (...args) {6 const key = JSON.stringify(args);7 if (cache[key] !== undefined) {8 return cache[key];9 }10 const result = fn(...args);11 cache[key] = result;12 return result;13 };14 }1516 // Fibonacci Function17 function fibonacci(n) {18 if (n <= 1) {19 return n;20 }21 return fibonacci(n - 1) + fibonacci(n - 2);22 }2324 // Memoized Fibonacci25 const memoizedFibonacci = memoize(fibonacci);2627 console.log(memoizedFibonacci(10)); // 5528 console.log(memoizedFibonacci(20)); // 67652930 // Currying Utility31 function curry(fn) {32 return function curried(...args) {33 if (args.length >= fn.length) {34 return fn(...args);35 }36 return function (...nextArgs) {37 return curried(...args, ...nextArgs);38 };39 };40 }4142 // Example Function for Currying43 function sum(a, b, c) {44 return a + b + c;45 }4647 // Curried Sum48 const curriedSum = curry(sum);4950 console.log(curriedSum(1)(2)(3)); // 651 console.log(curriedSum(1, 2)(3)); // 6
Key Takeaways
- Memoization improves performance by caching results of function calls using closures.
- Currying enables flexible function invocation by accumulating arguments over time.
- Both techniques leverage closures, highlighting their utility in JavaScript for functional programming and optimization.