Lodash _.memoize() method is used to memorize a given function by caching the result computed by the function. If the resolver is issued, the cache key for storing the result is determined based on the arguments given to the memoized method. By default, the first argument provided to the memoized function is used as the map cache key.
Syntax:
_.memoize(func, [resolver]);
Parameters:
- func: This parameter holds the function to have its output memoized.
- resolver: It is the function to resolve the cache key.
Return Value:
This method returns the new memoized function.
Example 1: In this example, we are printing the sum of the first 6 natural numbers by the use of the _.memoize() method.
Javascript
// Requiring the lodash library const _ = require( "lodash" ); // Use of _.memoize() method let sum = _.memoize( function (n) { return n < 1 ? n : n + sum(n - 1); }); // Sum of first 6 natural number console.log(sum(6)); |
Output:
21
Example 2: In this example, we are printing the values of the object by the use of the _.memoize() method.
Javascript
// Requiring the lodash library const _ = require( "lodash" ); let object = { 'cpp' : 5, 'java' : 8 }; // Use of _.memoize() method let values = _.memoize(_.values); // value of object console.log(values(object)); // Modify the result cache. values.cache.set(object, [ 'html' , 'css' ]); console.log(values(object)); |
Output:
[5, 8]
['html', 'css']