Lodash _.memoize() Method
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
const _ = require( "lodash" );
let sum = _.memoize( function (n) {
return n < 1 ? n : n + sum(n - 1);
});
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
const _ = require( "lodash" );
let object = { 'cpp' : 5, 'java' : 8 };
let values = _.memoize(_.values);
console.log(values(object));
values.cache.set(object, [ 'html' , 'css' ]);
console.log(values(object));
|
Output:
[5, 8]
['html', 'css']
Last Updated :
20 Oct, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...