Lodash – memoize method

  • Post author:
  • Post category:Lodash
  • Post comments:1 Comment
Lodash - memoize method

Syntax Of Lodash memoize method

_.memoize(func, [resolver])

Creates a function that Lodash memoizes method the result of func. If a resolver is provided, it determines the cache key for storing the result based on the arguments provided to the memoized function. By default, the first argument provided to the memoized function is used as the map cache key. The func is invoked with this binding of the memoized function.

Arguments

  • func (Function) โˆ’ The function to have its output memoized.
  • [resolver] (Function) โˆ’ The function to resolve the cache key.

Output

  • (Function) โˆ’ Returns the new memoized function.

Example

var _ = require('lodash');

var fibonacci = _.memoize(function(n) {
   return n < 2 ? n: fibonacci(n - 1) + fibonacci(n - 2);
});

var fibonacci1 = function(n) {
   return n < 2 ? n: fibonacci1(n - 1) + fibonacci1(n - 2);
};

var startTimestamp = new Date().getTime();
var result = fibonacci(1000);
var endTimestamp = new Date().getTime();
console.log(result + " in " + ((endTimestamp - startTimestamp)) + ' ms');

startTimestamp = new Date().getTime();
result = fibonacci1(30);
endTimestamp = new Date().getTime();
console.log(result + " in " + ((endTimestamp - startTimestamp)) + ' ms');

Save the above program in tester.js. Run the following command to execute this program.

Command

\>node tester.js

Output

4.346655768693743e+208 in 3 ms
832040 in 551 ms

Next Topic – Click Here

This Post Has One Comment

Leave a Reply