@Calendee

Understanding Lodash Memoize

I work on a team that has some really great developers. A few days ago in a PR review, I came across:

const formatNumberFull = memoize(number => numeral(number).format("0,0"));  

Ummm... what? The Lodash docs gave me a little better understanding of what memoize does, but I didn't really understand what was going on.

Here's the gist. Say you have an expensive operation that might be repeated frequently. Perhaps you're calculating factors. You don't want to have to perform that same operation over and over for the same number. Memoize effectively lets you cache the results of a function for the same arguments.

Trite Example:

function add(a, b) {  
  return a + b;
}

add(20, 5);  
add(10, 10);  
add(20, 5);  
add(10, 10);  
add(20, 5);  

If add were a really slow function, your app would needlessly come to a crawl. Instead of executing add over and over, Memoize lets your app cache the results for the same arguments. If you call add again with the same arguments, it returns the cached result instead of performing the expensive operation.

Memoize It

function add(a, b) {  
  return a + b;
}

var adder = _.memoize(add);

adder(20, 5);  
adder(10, 10);  
adder(20, 5);  
adder(10, 10);  
adder(20, 5);  

The adder "memoized" the add function. Now, each time adder is called, if the same arguments have been used, I'll get the results of the cache.

Here's a sample I put together that shows you exactly how to do this with a realistic scenario: