-
Notifications
You must be signed in to change notification settings - Fork 66
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
2 changed files
with
8 additions
and
8 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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. |