Skip to content

Commit

Permalink
Improve memoization section
Browse files Browse the repository at this point in the history
  • Loading branch information
Kikobeats committed Jan 3, 2017
1 parent 81d1b17 commit 3073d22
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 8 deletions.
2 changes: 1 addition & 1 deletion resources.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down
14 changes: 7 additions & 7 deletions workflow/memoization.md
Original file line number Diff line number Diff line change
@@ -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.

0 comments on commit 3073d22

Please sign in to comment.