The _.memoize() function is used to memorize a given function by caching the result computed by the function. It is used to speed up for the slow running process.
Syntax:
_.memoize(function, [hashFunction])
Parameters: This function accepts two parameters as mentioned above and described below:
- function: The function that need to be executed.
- hashFunction: It is an optional parameter. The hashFunction is used to compute the hash key for storing the result.
Return Value: It returns the result of the called function.
Below examples illustrate the _.memoize function in Underscore.js:
Example 1:
<!DOCTYPE html> <html> Â Â <head> Â Â Â Â <script type="text/javascript" src= Â Â Â Â </script> </head> Â Â <body> Â Â Â Â <script type="text/javascript"> Â Â Â Â Â Â Â Â Â Â var fib = _.memoize(function (n) { Â Â Â Â Â Â Â Â Â Â Â Â return n < 2 ? n : fib(n - 1) + fib(n - 2); Â Â Â Â Â Â Â Â }); Â Â Â Â Â Â Â Â Â Â console.log(fib(15)); Â Â Â Â </script> </body> Â Â </html> |
Output:
Example 2:
<!DOCTYPE html> <html> Â Â <head> Â Â Â Â <script type="text/javascript" src= Â Â Â Â </script> </head> Â Â <body> Â Â Â Â <script type="text/javascript"> Â Â Â Â Â Â Â Â Â Â var sum = _.memoize(function (n) { Â Â Â Â Â Â Â Â Â Â Â Â return n < 1 ? n : n + sum(n - 1); Â Â Â Â Â Â Â Â }); Â Â Â Â Â Â Â Â Â Â console.log('Sum of first 10 natural number: ' + sum(10)); Â Â Â Â </script> </body> Â Â </html> |
Output:

