DEV Community 👩‍💻👨‍💻

Cover image for Closures and Memoization
Matt
Matt

Posted on

Closures and Memoization

Hi dev.to! Today I'm writing about closures and one interesting way they can be used.

You've probably seen this slow implementation of the Fibonacci series before:

// O(2^N) time
function fib(n) {
  if (n === 0) return 0;
  if (n < 3) return 1;

  return fib(n - 1) + fib(n - 2);
Enter fullscreen mode Exit fullscreen mode

We can rewrite the solution to make it run faster, or we can leverage higher order functions to do the hard work for us.

function memoize(cb) {
  const cache = {};
  return function (...args) {
    const key = args.join('-');
    if (!(key in cache)) cache[key] = cb(...args);
    return cache[key];
  };
}

// now fib is O(N) time!
fib = memoize(fib);
Enter fullscreen mode Exit fullscreen mode

If this is confusing - don't worry! There's a lot going on here, but once you become more familiar with closures writing code like this will feel natural.

I go into detail about how this works in the following video: https://www.youtube.com/watch?v=9Iyj-foHNmQ

Thanks for reading. Of course, there's plenty more advanced use cases for closures such as callbacks in react component and debouncing. I'd like to hear about any nifty closure use cases you've come across.

Top comments (0)

🌚 Browsing with dark mode makes you a better developer.

It's a scientific fact.