File tree Expand file tree Collapse file tree 1 file changed +24
-5
lines changed
Expand file tree Collapse file tree 1 file changed +24
-5
lines changed Original file line number Diff line number Diff line change 11/**
22 * Memoize
3- * @param {Function } fn
4- * @returns
3+ *
4+ * From [Wikipedia](https://en.wikipedia.org/wiki/Memoization),
5+ * memoization is an optimization technique
6+ * used primarily to speed up computer programs,
7+ * by storing the results of expensive function calls
8+ * and returning the cached result when the same inputs occur again
9+ *
10+ * This function is a first class objects,
11+ * which lets us use it as [Higher-Order Function](https://eloquentjavascript.net/05_higher_order.html)
12+ * and return another function
13+ *
14+ * @param {Function } func Original function
15+ * @returns {Function } Memoized function
516 */
617export const memoize = ( func ) => {
7- // Initializing new cache
18+ // Initialization of a slot to store the function result
819 const cache = { }
920
1021 return ( ...args ) => {
22+ // Retrieving the first argument of the function
1123 const [ arg ] = args
1224
25+ /**
26+ * Checks if the argument is already present in the cache,
27+ * then return the associated value / result
28+ */
1329 if ( arg in cache ) {
14- // Reading cache by argument
1530 return cache [ arg ]
1631 }
1732
18- // Updating cache by argument
33+ /**
34+ * If the argument is not yet present in the cache,
35+ * execute original function and save its value / result in cache,
36+ * finally return it
37+ */
1938 const result = func ( arg )
2039 cache [ arg ] = result
2140 return result
You can’t perform that action at this time.
0 commit comments