From 89102ea9ac49769edbb2e8e9c1a74ceee26e2a52 Mon Sep 17 00:00:00 2001 From: atomiks Date: Sun, 31 Dec 2017 22:55:55 +1100 Subject: [PATCH 1/2] Add memoize snippet --- snippets/memoize.md | 23 +++++++++++++++++++++++ tag_database | 1 + 2 files changed, 24 insertions(+) create mode 100644 snippets/memoize.md diff --git a/snippets/memoize.md b/snippets/memoize.md new file mode 100644 index 000000000..8a71702e1 --- /dev/null +++ b/snippets/memoize.md @@ -0,0 +1,23 @@ +### memoize + +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'). +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. + +```js +const memoize = fn => { + const cache = Object.create(null); + return value => cache[value] || (cache[value] = fn(value)); +}; +``` + +```js +// See the `anagrams` snippet. +const anagramsCached = memoize(anagrams); +anagramsCached('javascript'); // takes a long time +anagramsCached('javascript'); // returns virtually instantly since it's now cached +``` diff --git a/tag_database b/tag_database index d897e319c..f82dd92c5 100644 --- a/tag_database +++ b/tag_database @@ -81,6 +81,7 @@ lowercaseKeys:object mapObject:array max:math median:math +memoize:function min:math negate:logic nthElement:array From 19247593da3c13be95a173937e7a3ed7e60abfc1 Mon Sep 17 00:00:00 2001 From: Angelos Chalaris Date: Sun, 31 Dec 2017 14:04:44 +0200 Subject: [PATCH 2/2] Update memoize.md --- snippets/memoize.md | 7 ++----- 1 file changed, 2 insertions(+), 5 deletions(-) diff --git a/snippets/memoize.md b/snippets/memoize.md index 8a71702e1..c1b6b1343 100644 --- a/snippets/memoize.md +++ b/snippets/memoize.md @@ -2,11 +2,8 @@ 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'). -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. +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'`). +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. ```js const memoize = fn => {