Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commitd246958

Browse files
authored
merge: Added explicit cache feature & optional parameter (TheAlgorithms#941)
1 parentad68c63 commitd246958

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-
constmemoize=(func)=>{
16-
// Initialization of a slot to store the function result by arguments as a key in Hash Map
17-
constcache=newMap()
18-
16+
constmemoize=(func,cache=newMap())=>{
1917
constjsonReplacer=(_,value)=>{
2018
if(valueinstanceofSet){// 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+
importLFUCachefrom'../LFUCache'
56

67
constmultipleFactorials=(arr)=>arr.map(factorial)
78

@@ -51,4 +52,17 @@ describe('Testing Memoize', () => {
5152
expect(memoUnion(...inputs)).toEqual(newSet([1,2,3,4,5,6]))
5253
expect(memoUnion(...inputs)).toEqual(union(...inputs))
5354
})
55+
56+
it('Testing with explicit cache -> LFUCache',()=>{
57+
constLFU=newLFUCache(2)
58+
59+
constmemoizeFibonacci=memoize(fibonacci,LFU)// added LFU cache explicitly
60+
constfibOfFiveHundred=memoizeFibonacci(500)
61+
constfibOfOneHundred=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)

[8]ページ先頭

©2009-2025 Movatter.jp