From 0589fc19e0d18b43f65b315d7b99976503594df6 Mon Sep 17 00:00:00 2001 From: Damien Chazoule Date: Tue, 5 Oct 2021 10:37:14 +0200 Subject: [PATCH] Added comments about memoization --- Cache/Memoize.js | 29 ++++++++++++++++++++++++----- 1 file changed, 24 insertions(+), 5 deletions(-) diff --git a/Cache/Memoize.js b/Cache/Memoize.js index 36309cbb3..9bd998fda 100644 --- a/Cache/Memoize.js +++ b/Cache/Memoize.js @@ -1,21 +1,40 @@ /** * Memoize - * @param {Function} fn - * @returns + * + * From [Wikipedia](https://en.wikipedia.org/wiki/Memoization), + * memoization is an optimization technique + * used primarily to speed up computer programs, + * by storing the results of expensive function calls + * and returning the cached result when the same inputs occur again + * + * This function is a first class objects, + * which lets us use it as [Higher-Order Function](https://eloquentjavascript.net/05_higher_order.html) + * and return another function + * + * @param {Function} func Original function + * @returns {Function} Memoized function */ export const memoize = (func) => { - // Initializing new cache + // Initialization of a slot to store the function result const cache = {} return (...args) => { + // Retrieving the first argument of the function const [arg] = args + /** + * Checks if the argument is already present in the cache, + * then return the associated value / result + */ if (arg in cache) { - // Reading cache by argument return cache[arg] } - // Updating cache by argument + /** + * If the argument is not yet present in the cache, + * execute original function and save its value / result in cache, + * finally return it + */ const result = func(arg) cache[arg] = result return result