Skip to content
Related Articles
Open in App
Not now

Related Articles

Lodash _.memoize() Method

Improve Article
Save Article
Like Article
  • Last Updated : 16 Sep, 2020
Improve Article
Save Article
Like Article

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:

_.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
Like Article
Save Article
Related Articles

Start Your Coding Journey Now!