Merge pull request #457 from Chalarangelo/atomiks-patch-1
[UPDATE] memoize.md
This commit is contained in:
@ -2,13 +2,20 @@
|
|||||||
|
|
||||||
Returns the memoized (cached) function.
|
Returns the memoized (cached) function.
|
||||||
|
|
||||||
Use `Object.create(null)` to create an empty object without `Object.prototype` (so that those properties are not resolved if the input value is something like `'hasOwnProperty'`).
|
Create an empty cache by instantiating a new `Map` object.
|
||||||
Return a function which takes a single argument to be supplied to the memoized function by first checking if the function's output for that specific input value is already cached, or store and return it if not.
|
Return a function which takes a single argument to be supplied to the memoized function by first checking if the function's output for that specific input value is already cached, or store and return it if not. The `function` keyword must be used in order to allow the memoized function to have its `this` context changed if necessary.
|
||||||
|
Allow access to the `cache` by setting it as a property on the returned function.
|
||||||
|
|
||||||
```js
|
```js
|
||||||
const memoize = fn => {
|
const memoize = fn => {
|
||||||
const cache = Object.create(null);
|
const cache = new Map();
|
||||||
return value => cache[value] || (cache[value] = fn(value));
|
const cached = function(val) {
|
||||||
|
return cache.has(val)
|
||||||
|
? cache.get(val)
|
||||||
|
: cache.set(val, fn.call(this, val)) && cache.get(val);
|
||||||
|
};
|
||||||
|
cached.cache = cache;
|
||||||
|
return cached;
|
||||||
};
|
};
|
||||||
```
|
```
|
||||||
|
|
||||||
@ -17,4 +24,5 @@ const memoize = fn => {
|
|||||||
const anagramsCached = memoize(anagrams);
|
const anagramsCached = memoize(anagrams);
|
||||||
anagramsCached('javascript'); // takes a long time
|
anagramsCached('javascript'); // takes a long time
|
||||||
anagramsCached('javascript'); // returns virtually instantly since it's now cached
|
anagramsCached('javascript'); // returns virtually instantly since it's now cached
|
||||||
|
console.log(anagramsCached.cache); // Map
|
||||||
```
|
```
|
||||||
|
|||||||
Reference in New Issue
Block a user