File tree Expand file tree Collapse file tree 2 files changed +66
-0
lines changed
Expand file tree Collapse file tree 2 files changed +66
-0
lines changed Original file line number Diff line number Diff line change 1+ /**
2+ * Memoize
3+ * @param {Function } fn
4+ * @returns
5+ */
6+ export const memoize = ( func ) => {
7+ // eslint-disable-next-line no-console
8+ console . log ( `Creating cache for function '${ func . name } '` )
9+
10+ const cache = { }
11+
12+ return ( ...args ) => {
13+ const [ arg ] = args
14+
15+ if ( arg in cache ) {
16+ // eslint-disable-next-line no-console
17+ console . log ( `Reading cache with argument ${ arg } ` )
18+
19+ return cache [ arg ]
20+ }
21+
22+ // eslint-disable-next-line no-console
23+ console . log ( `Updating cache with argument ${ arg } ` )
24+
25+ const result = func ( arg )
26+ cache [ arg ] = result
27+ return result
28+ }
29+ }
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 ( 3_628_800 )
36+ } )
37+ } )
You can’t perform that action at this time.
0 commit comments