JavaScript Development Space

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 Utility
2 function memoize(fn) {
3 const cache = {};
4
5 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 }
15
16 // Fibonacci Function
17 function fibonacci(n) {
18 if (n <= 1) {
19 return n;
20 }
21 return fibonacci(n - 1) + fibonacci(n - 2);
22 }
23
24 // Memoized Fibonacci
25 const memoizedFibonacci = memoize(fibonacci);
26
27 console.log(memoizedFibonacci(10)); // 55
28 console.log(memoizedFibonacci(20)); // 6765
29
30 // Currying Utility
31 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 }
41
42 // Example Function for Currying
43 function sum(a, b, c) {
44 return a + b + c;
45 }
46
47 // Curried Sum
48 const curriedSum = curry(sum);
49
50 console.log(curriedSum(1)(2)(3)); // 6
51 console.log(curriedSum(1, 2)(3)); // 6

Key Takeaways

  1. Memoization improves performance by caching results of function calls using closures.
  2. Currying enables flexible function invocation by accumulating arguments over time.
  3. Both techniques leverage closures, highlighting their utility in JavaScript for functional programming and optimization.
JavaScript Development Space

© 2025 JavaScript Development Space - Master JS and NodeJS. All rights reserved.