Skip to content
Advertisement

Memoize a curried function

JavaScript

Is it possible to memoize f with regard to the 2 arguments, namely:

JavaScript

Advertisement

Answer

You could take a Map as cache and take nested maps for all following arguments.

This cache works for arbitrary count of arguments and reuses the values from the former calls.

It works by taking a curried function and an optional Map. If the map is not supplied, a new map is created which serves as base cache for all other calls of the returned closure or the final result.

The inner function takes a single argument and checks if this value is in the map.

  • If not, call the curried function and check the returned value

    • if function, create a new closure over the function and a new map,

    • if no function take the result,

    as value for a new element of the map.

  • Finally return the value from the map.

JavaScript
JavaScript
Advertisement