Memoization in Javascript

Kapil Thukral
1 min readAug 30, 2021

Objective: Building a Higher Order function that returns the input function with memoization superpower.

This evolved version of the input function will cache the output corresponding to the given input, so that if in future we receive the same input then the corresponding output is not reevaluated but rather served from cache.

For example, if we have a function “add” which takes in numbers to add as input and returns the sum of those input numbers. So add(1,2,3) when called for the first time evaluates the sum 6, stores the result in the cache for the corresponding input and returns 6, and when add(1,2,3) is called in future, then because add function was already evaluated for (1,2,3), therefore it’s result will be served from the cache.

Note: We are using closure and storing/caching the output in memcache.

Things to take care of:

  1. What should be the cache size? The maximum number of inputs for which you will be storing their corresponding outputs.
  2. How to generate the key from the inputs to be stored in memCache? (The approach we followed above was to concatenate all input arguments using a separator ‘|’, a better way can be to use some hash function and apply them on input arguments)

--

--