Skip to content
Related Articles

Related Articles

Save Article
Improve Article
Save Article
Like Article

Lodash _.memoize() Method

  • Last Updated : 16 Sep, 2020

The _.memoize() method is used to memorize a given function by caching the result computed by the function. If resolver is issued, the cache key for store 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:

Hey geek! The constant emerging technologies in the world of web development always keeps the excitement for this subject through the roof. But before you tackle the big projects, we suggest you start by learning the basics. Kickstart your web development journey by learning JS concepts with our JavaScript Course. Now at it's lowest price ever!

_.memoize(func, [resolver])

Parameters: This method accepts two parameters as mentioned above and described below:

  • 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.



Note: Here, const _ = require(‘lodash’) is used to import the lodash library into the file. 
 

Example 1:

Javascript




// Requiring the lodash library  
const _ = require("lodash");  
  
// Use of _.memoize() method  
var 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:  

Javascript




// Requiring the lodash library  
const _ = require("lodash");  
  
var object = { 'cpp': 5, 'java': 8 };
  
// Use of _.memoize() method  
var 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']

Note: This will not work in normal JavaScript because it requires the library lodash to be installed.




My Personal Notes arrow_drop_up
Recommended Articles
Page :