File tree Expand file tree Collapse file tree 2 files changed +79
-0
lines changed Expand file tree Collapse file tree 2 files changed +79
-0
lines changed Original file line number Diff line number Diff line change 1+ /**
2+ * Memoize
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
16+ */
17+ export const memoize = ( func ) => {
18+ // Initialization of a slot to store the function result
19+ const cache = { }
20+
21+ return ( ...args ) => {
22+ // Retrieving the first argument of the function
23+ const [ arg ] = args
24+
25+ /**
26+ * Checks if the argument is already present in the cache,
27+ * then return the associated value / result
28+ */
29+ if ( arg in cache ) {
30+ return cache [ arg ]
31+ }
32+
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+ */
38+ const result = func ( arg )
39+ cache [ arg ] = result
40+ return result
41+ }
42+ }
Original file line number Diff line number Diff line change 1+ import { memoize } from '../Memoize'
2+
3+ const fibonacci = ( n ) => {
4+ if ( n < 2 ) {
5+ return n
6+ }
7+
8+ return fibonacci ( n - 2 ) + fibonacci ( n - 1 )
9+ }
10+
11+ const factorial = ( n ) => {
12+ if ( n === 0 ) {
13+ return 1
14+ }
15+
16+ return n * factorial ( n - 1 )
17+ }
18+
19+ describe ( 'Memoize' , ( ) => {
20+ it ( 'expects the fibonacci function to use the cache on the second call' , ( ) => {
21+ const memoFibonacci = memoize ( fibonacci )
22+
23+ expect ( memoFibonacci ( 5 ) ) . toEqual ( fibonacci ( 5 ) )
24+ expect ( memoFibonacci ( 5 ) ) . toEqual ( 5 )
25+ expect ( memoFibonacci ( 10 ) ) . toEqual ( fibonacci ( 10 ) )
26+ expect ( memoFibonacci ( 10 ) ) . toEqual ( 55 )
27+ } )
28+
29+ it ( 'expects the factorial function to use the cache on the second call' , ( ) => {
30+ const memoFactorial = memoize ( factorial )
31+
32+ expect ( memoFactorial ( 5 ) ) . toEqual ( factorial ( 5 ) )
33+ expect ( memoFactorial ( 5 ) ) . toEqual ( 120 )
34+ expect ( memoFactorial ( 10 ) ) . toEqual ( factorial ( 10 ) )
35+ expect ( memoFactorial ( 10 ) ) . toEqual ( 3628800 )
36+ } )
37+ } )
You can’t perform that action at this time.
0 commit comments