Question: 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 back the cached result data using the key. Below is my implementation:

Javascript code:

```
var cdata = $http
.get(HOST_URL + "/v1/report/states")
.success(function(data) {
    //put the result in the angularJs scope object. 
    $scope.states = data;
});

//store the result in the cache.
var cachedResult = _.memoize(
    function() {
        return cdata;
    }, "states");

```

Is my usage of memoize to store the result of ajax is correct. Also once it is put in cache, how to retrieve based on the key. i.e 'states'.

Answer: 
[`_.memoize`](http://underscorejs.org/#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.
If you are using Angular.js's `$http`, you probably just want to pass `{cache : true}` as a second parameter to the `get` method.

To store values using key value pairs, you may want to use [$cacheFactory](https://docs.angularjs.org/api/ng/type/$cacheFactory.Cache), as described in other answers like [here](https://stackoverflow.com/questions/14117653/how-to-cache-an-http-get-service-in-angularjs). Basically:

```
var cache = $cacheFactory('cacheId');
cache.put('states', 'value');
cache.get('states');

```