Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 2 additions & 4 deletions Cache/Memoize.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,12 +10,10 @@
* which lets us use it as [Higher-Order Function](https://eloquentjavascript.net/05_higher_order.html)
* and return another function
* @param {Function} func Original function
* @param {Map} cache - it's receive any cache DS which have get, set & has method
* @returns {Function} Memoized function
*/
const memoize = (func) => {
// Initialization of a slot to store the function result by arguments as a key in Hash Map
const cache = new Map()

const memoize = (func, cache = new Map()) => {
const jsonReplacer = (_, value) => {
if (value instanceof Set) { // if the value is Set it's converted to Array cause JSON.stringify can't convert Set
return [...value]
Expand Down
14 changes: 14 additions & 0 deletions Cache/test/Memoize.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { memoize } from '../Memoize'
import { union } from './cacheTest'
import { fibonacci } from '../../Dynamic-Programming/FibonacciNumber'
import { factorial } from '../../Recursive/Factorial'
import LFUCache from '../LFUCache'

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

Expand Down Expand Up @@ -51,4 +52,17 @@ describe('Testing Memoize', () => {
expect(memoUnion(...inputs)).toEqual(new Set([1, 2, 3, 4, 5, 6]))
expect(memoUnion(...inputs)).toEqual(union(...inputs))
})

it('Testing with explicit cache -> LFUCache', () => {
const LFU = new LFUCache(2)

const memoizeFibonacci = memoize(fibonacci, LFU) // added LFU cache explicitly
const fibOfFiveHundred = memoizeFibonacci(500)
const fibOfOneHundred = memoizeFibonacci(100)

expect(memoizeFibonacci(500)).toBe(fibOfFiveHundred)
expect(memoizeFibonacci(100)).toBe(fibOfOneHundred)

expect(LFU.leastFrequency).toBe(2)
})
})