using memoize function with underscore.js

前端 未结 3 1928
猫巷女王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 18:51

    _.memoize takes a function:

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

    You should understand that this is just an extra wrapper function that makes function that you pass it as an argument smarter( Adds extra mapping object to it ).

    In example above function that computes fibonacci number is wrapped around with _.memoize. So on every function call (fibonacci(5) or fibonacci(55555)) passed argument matched to return value so if you need to call one more time fibonacci(55555) it doesn't need to compute it again. It just fetches that value from that mapping object that _.memoize provided internally.

提交回复
热议问题