11import { memoize } from '../Memoize'
2+ import { fibonacci } from '../../Dynamic-Programming/FibonacciNumber'
3+ import { factorial } from '../../Recursive/Factorial'
24
3- const fibonacci = ( n ) => {
4- if ( n < 2 ) {
5- return n
6- }
5+ const multipleFactorials = ( arr ) => arr . map ( factorial )
76
8- return fibonacci ( n - 2 ) + fibonacci ( n - 1 )
7+ /**
8+ * @title implementation of union function
9+ * @param {Set } sets
10+ * @return {new Set }
11+ */
12+ function union ( ...sets ) {
13+ return new Set (
14+ sets . reduce ( ( flatArray , set ) => [ ...flatArray , ...set ] , [ ] )
15+ )
916}
1017
11- const factorial = ( n ) => {
12- if ( n === 0 ) {
13- return 1
14- }
15-
16- return n * factorial ( n - 1 )
17- }
18-
19- describe ( 'Memoize' , ( ) => {
18+ describe ( 'Testing Memoize' , ( ) => {
2019 it ( 'expects the fibonacci function to use the cache on the second call' , ( ) => {
2120 const memoFibonacci = memoize ( fibonacci )
2221
@@ -34,4 +33,32 @@ describe('Memoize', () => {
3433 expect ( memoFactorial ( 10 ) ) . toEqual ( factorial ( 10 ) )
3534 expect ( memoFactorial ( 10 ) ) . toEqual ( 3628800 )
3635 } )
36+
37+ it ( 'expects the multipleFactorials function to use the cache on the second call' , ( ) => {
38+ const memoMultipleFactorials = memoize ( multipleFactorials )
39+ const input = [ 2 , 3 , 4 , 5 ]
40+
41+ expect ( memoMultipleFactorials ( input ) ) . toEqual ( [ 2 , 6 , 24 , 120 ] )
42+ expect ( memoMultipleFactorials ( input ) ) . toEqual ( multipleFactorials ( input ) )
43+ } )
44+
45+ it ( 'expects the multipleFactorials function to use the cache on the second call' , ( ) => {
46+ const memoMultipleFactorials = memoize ( multipleFactorials )
47+ const input = [ 2 , 3 , 4 , 5 ]
48+
49+ expect ( memoMultipleFactorials ( input ) ) . toEqual ( [ 2 , 6 , 24 , 120 ] )
50+ expect ( memoMultipleFactorials ( input ) ) . toEqual ( multipleFactorials ( input ) )
51+ } )
52+
53+ it ( 'expects the union function to use the cache on the second call' , ( ) => {
54+ const memoUnion = memoize ( union )
55+ const inputs = [
56+ new Set ( [ 1 , 2 , 3 ] ) ,
57+ new Set ( [ 4 , 3 , 2 ] ) ,
58+ new Set ( [ 5 , 3 , 6 ] )
59+ ]
60+
61+ expect ( memoUnion ( ...inputs ) ) . toEqual ( new Set ( [ 1 , 2 , 3 , 4 , 5 , 6 ] ) )
62+ expect ( memoUnion ( ...inputs ) ) . toEqual ( union ( ...inputs ) )
63+ } )
3764} )
0 commit comments