Last Updated : 03 Sep, 2024
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:
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']
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4