From f70595f36cbc62ce4fe6b7fe4975b9169dbf5070 Mon Sep 17 00:00:00 2001 From: atomiks Date: Wed, 3 Jan 2018 05:10:16 +1100 Subject: [PATCH] Update memoize.md --- snippets/memoize.md | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/snippets/memoize.md b/snippets/memoize.md index 7df16e542..856375a69 100644 --- a/snippets/memoize.md +++ b/snippets/memoize.md @@ -3,13 +3,17 @@ Returns the memoized (cached) function. 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 const memoize = fn => { const cache = new Map(); - const cached = val => cache.has(val) ? cache.get(val) : (cache.set(val, fn(val)) && cache.get(val)); + 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; };