DEV Community

Dharan Ganesan
Dharan Ganesan

Posted on

Day 46: Memoization

What is Memoization?

Memoization is a technique used to store the results of expensive function calls and return the cached result when the same inputs occur again. It's like having a crystal ball that remembers previous calculations and can instantly provide answers.
🪄

Creating the Memoization Decorator

Let's create a TypeScript decorator that can memoize the result of a function. We'll call it @memoize. 📝

function memoize(target: any, key: string, descriptor: PropertyDescriptor) {
  const originalMethod = descriptor.value;
  const cache = new Map();

  descriptor.value = function (...args: any[]) {
    const key = JSON.stringify(args);
    if (cache.has(key)) {
      return cache.get(key);
    }

    const result = originalMethod.apply(this, args);
    cache.set(key, result);
    return result;
  };

  return descriptor;
}
Enter fullscreen mode Exit fullscreen mode

Applying Decorator

class Calculator {
  @memoize
  static fibonacci(n: number): number {
    if (n <= 1) return n;
    return this.fibonacci(n - 1) + this.fibonacci(n - 2);
  }
}
Enter fullscreen mode Exit fullscreen mode

By adding @memoize to the fibonacci method, we're telling it to cache the results. As a result, subsequent calls with the same argument won't recalculate the Fibonacci number, making our code much faster! 🚀

Example

console.log(Calculator.fibonacci(40)); // Calculates Fibonacci(40) and caches it
console.log(Calculator.fibonacci(40)); // Returns the cached result instantly
Enter fullscreen mode Exit fullscreen mode

Benefits of Memoization with Decorators

  • Performance Boost: Memoization can drastically reduce the execution time of functions with expensive calculations.
  • Simplified Code: You don't need to manually implement caching logic in your functions; decorators handle it for you.
  • Readability: Code using decorators is more concise and easier to understand.

Considerations

  • Be cautious when using memoization for functions with a large number of potential input values, as it can lead to excessive memory usage. Always evaluate your use case.

SurveyJS custom survey software

JavaScript UI Libraries for Surveys and Forms

SurveyJS lets you build a JSON-based form management system that integrates with any backend, giving you full control over your data and no user limits. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more.

Learn more

Top comments (0)

Image of Docusign

🛠️ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more