using memoize function with underscore.js

前端 未结 3 1930
猫巷女王i
猫巷女王i 2021-02-05 18:05

I am trying to cache the result from an ajax call using memoize function from Underscore.js. I am not sure of my implementation. Also how to retrieve b

3条回答
  •  情书的邮戳
    2021-02-05 19:04

    Let us understand how _.memoize works, it takes a function which needs to be memoized as first argument and caches the result of the function return for given parameter. Next time if the memoized function is invoked with same argument it will use cached result and the execution time for the function can be avoided. So it is very important to reduce the computation time.

    As mentioned, the above fibonaci function it memoized works perfectly fine as the argument has a primitive type.

    The problem occurs when you have to memoize a function which accepts an object. To solve this, _.memoize accepts an optional argument hashFunction which will be used to hash the input. This way you can uniquely identify your objects with your own hash functions.

    The default implementation of _.memoize (using the default hash function) returns the first argument as it is - in the case of JavaScript it will return [Object object].

    So for e.g.

    var fn = function (obj){ some computation here..}
    var memoizedFn = _.memoize(fn);
    
    memoizedFn({"id":"1"}) // we will get result, and result is cahced now
    
    memoizedFn({"id":"2"}) // we will get cached result which is wrong
    

    why default has function in _.memoize is function(x) {return x}

    the problem can be avoided by passing a hash function

    _.memoize(fn, function(input){return JSON.stringify(input)});
    

    This was a real help for me when I was using _.memoize for a function that was working on arrays arguments.

    Hope this helps many people in their work.

提交回复
热议问题