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']
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
20 Oct, 2023
Like Article
Save Article