diff --git a/Cache/Memoize.js b/Cache/Memoize.js index c69ae48011..94bc0f28ea 100644 --- a/Cache/Memoize.js +++ b/Cache/Memoize.js @@ -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] diff --git a/Cache/test/Memoize.test.js b/Cache/test/Memoize.test.js index 5d5948c489..7ce4d03529 100644 --- a/Cache/test/Memoize.test.js +++ b/Cache/test/Memoize.test.js @@ -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) @@ -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) + }) }) pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy