mirror of
https://github.com/TheAlgorithms/JavaScript.git
synced 2025-07-04 15:39:42 +08:00
Feat: Added Memoize Func
This commit is contained in:
29
Cache/Memoize.js
Normal file
29
Cache/Memoize.js
Normal file
@ -0,0 +1,29 @@
|
||||
/**
|
||||
* Memoize
|
||||
* @param {Function} fn
|
||||
* @returns
|
||||
*/
|
||||
export const memoize = (func) => {
|
||||
// eslint-disable-next-line no-console
|
||||
console.log(`Creating cache for function '${func.name}'`)
|
||||
|
||||
const cache = {}
|
||||
|
||||
return (...args) => {
|
||||
const [arg] = args
|
||||
|
||||
if (arg in cache) {
|
||||
// eslint-disable-next-line no-console
|
||||
console.log(`Reading cache with argument ${arg}`)
|
||||
|
||||
return cache[arg]
|
||||
}
|
||||
|
||||
// eslint-disable-next-line no-console
|
||||
console.log(`Updating cache with argument ${arg}`)
|
||||
|
||||
const result = func(arg)
|
||||
cache[arg] = result
|
||||
return result
|
||||
}
|
||||
}
|
37
Cache/__tests__/Memoize.test.js
Normal file
37
Cache/__tests__/Memoize.test.js
Normal file
@ -0,0 +1,37 @@
|
||||
import { memoize } from '../Memoize'
|
||||
|
||||
const fibonacci = (n) => {
|
||||
if (n < 2) {
|
||||
return n
|
||||
}
|
||||
|
||||
return fibonacci(n - 2) + fibonacci(n - 1)
|
||||
}
|
||||
|
||||
const factorial = (n) => {
|
||||
if (n === 0) {
|
||||
return 1
|
||||
}
|
||||
|
||||
return n * factorial(n - 1)
|
||||
}
|
||||
|
||||
describe('memoize', () => {
|
||||
it('expects the fibonacci function to use the cache on the second call', () => {
|
||||
const memoFibonacci = memoize(fibonacci)
|
||||
|
||||
expect(memoFibonacci(5)).toEqual(fibonacci(5))
|
||||
expect(memoFibonacci(5)).toEqual(5)
|
||||
expect(memoFibonacci(10)).toEqual(fibonacci(10))
|
||||
expect(memoFibonacci(10)).toEqual(55)
|
||||
})
|
||||
|
||||
it('expects the factorial function to use the cache on the second call', () => {
|
||||
const memoFactorial = memoize(factorial)
|
||||
|
||||
expect(memoFactorial(5)).toEqual(factorial(5))
|
||||
expect(memoFactorial(5)).toEqual(120)
|
||||
expect(memoFactorial(10)).toEqual(factorial(10))
|
||||
expect(memoFactorial(10)).toEqual(3_628_800)
|
||||
})
|
||||
})
|
Reference in New Issue
Block a user