Skip to content

Commit d246958

Browse files
authored
merge: Added explicit cache feature & optional parameter (TheAlgorithms#941)
1 parent ad68c63 commit d246958

File tree

2 files changed

+16
-4
lines changed

2 files changed

+16
-4
lines changed

Cache/Memoize.js

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -10,12 +10,10 @@
1010
* which lets us use it as [Higher-Order Function](https://eloquentjavascript.net/05_higher_order.html)
1111
* and return another function
1212
* @param {Function} func Original function
13+
* @param {Map} cache - it's receive any cache DS which have get, set & has method
1314
* @returns {Function} Memoized function
1415
*/
15-
const memoize = (func) => {
16-
// Initialization of a slot to store the function result by arguments as a key in Hash Map
17-
const cache = new Map()
18-
16+
const memoize = (func, cache = new Map()) => {
1917
const jsonReplacer = (_, value) => {
2018
if (value instanceof Set) { // if the value is Set it's converted to Array cause JSON.stringify can't convert Set
2119
return [...value]

Cache/test/Memoize.test.js

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ import { memoize } from '../Memoize'
22
import { union } from './cacheTest'
33
import { fibonacci } from '../../Dynamic-Programming/FibonacciNumber'
44
import { factorial } from '../../Recursive/Factorial'
5+
import LFUCache from '../LFUCache'
56

67
const multipleFactorials = (arr) => arr.map(factorial)
78

@@ -51,4 +52,17 @@ describe('Testing Memoize', () => {
5152
expect(memoUnion(...inputs)).toEqual(new Set([1, 2, 3, 4, 5, 6]))
5253
expect(memoUnion(...inputs)).toEqual(union(...inputs))
5354
})
55+
56+
it('Testing with explicit cache -> LFUCache', () => {
57+
const LFU = new LFUCache(2)
58+
59+
const memoizeFibonacci = memoize(fibonacci, LFU) // added LFU cache explicitly
60+
const fibOfFiveHundred = memoizeFibonacci(500)
61+
const fibOfOneHundred = memoizeFibonacci(100)
62+
63+
expect(memoizeFibonacci(500)).toBe(fibOfFiveHundred)
64+
expect(memoizeFibonacci(100)).toBe(fibOfOneHundred)
65+
66+
expect(LFU.leastFrequency).toBe(2)
67+
})
5468
})

0 commit comments

Comments
 (0)