diff --git a/resources.md b/resources.md index a94c6f8..1410384 100644 --- a/resources.md +++ b/resources.md @@ -7,7 +7,7 @@ #### Cache -* [lru-cache](https://github.com/isaacs/node-lru-cache) – A `Map` cache that deletes the least-recently-used items. +* [lru](https://github.com/chriso/lru) – A simple LRU cache supporting O(1) set, get and eviction of old keys. * [async-cache](https://github.com/isaacs/async-cache) – Cache your async lookups and don't fetch the same thing more than necessary. * [mem](https://github.com/sindresorhus/mem) - An optimization used to speed up consecutive function calls. diff --git a/workflow/memoization.md b/workflow/memoization.md index 6683e45..1e0a054 100644 --- a/workflow/memoization.md +++ b/workflow/memoization.md @@ -1,17 +1,17 @@ -# Memoization: Cache successive calls. +# Memoization: Cache successive calls Just calculate the value of something once and reuse the value. This avoids the cost of recalculating the same value. -If you need to control a set of small values, you can use a `Map`: - ```js -var cache = new Map() - +var cache = Object.create(null) var cityOne = 'Murcia' var cityTwo = 'Madrid' var routeName = `${cityOne}${cityTwo}` - if (!cache.has(routeName)) cache.set(routeName, getDistance(cityOne, cityTwo)) ``` -A more complex, but better solution, would be to control the size of the `Map`. One example would be to use an LRU cache. +Notes that first line is `Object.create(null)`. This create a `Object` without `prototype`. because we want a pure object for be used as a Hash Table (with all the [prototypical method](https://developer.mozilla.org/es/docs/Web/JavaScript/Referencia/Objetos_globales/Object/prototype) missing). + +If you need more control about your cache, you can create it using Map or WeakMap structures. Specially use it when you want to remove items from the cache. + +[LRU](https://www.npmjs.com/package/lru) or [mem](https://www.npmjs.com/package/mem) are good high level libraries that implement this technique.