mirror of
https://github.com/TheAlgorithms/JavaScript.git
synced 2025-07-05 08:16:50 +08:00
merge: Improved Memoize
function (#912)
* feat: improved memoize function used Map instead of object & used the JSON.stringfy method for generate a valid string as a key * docs: modified documentation * style: format with standard * docs: modified stringify doc * refactor: remove two repetition implementation
This commit is contained in:
@ -1,22 +1,21 @@
|
||||
import { memoize } from '../Memoize'
|
||||
import { fibonacci } from '../../Dynamic-Programming/FibonacciNumber'
|
||||
import { factorial } from '../../Recursive/Factorial'
|
||||
|
||||
const fibonacci = (n) => {
|
||||
if (n < 2) {
|
||||
return n
|
||||
}
|
||||
const multipleFactorials = (arr) => arr.map(factorial)
|
||||
|
||||
return fibonacci(n - 2) + fibonacci(n - 1)
|
||||
/**
|
||||
* @title implementation of union function
|
||||
* @param {Set} sets
|
||||
* @return {new Set}
|
||||
*/
|
||||
function union (...sets) {
|
||||
return new Set(
|
||||
sets.reduce((flatArray, set) => [...flatArray, ...set], [])
|
||||
)
|
||||
}
|
||||
|
||||
const factorial = (n) => {
|
||||
if (n === 0) {
|
||||
return 1
|
||||
}
|
||||
|
||||
return n * factorial(n - 1)
|
||||
}
|
||||
|
||||
describe('Memoize', () => {
|
||||
describe('Testing Memoize', () => {
|
||||
it('expects the fibonacci function to use the cache on the second call', () => {
|
||||
const memoFibonacci = memoize(fibonacci)
|
||||
|
||||
@ -34,4 +33,32 @@ describe('Memoize', () => {
|
||||
expect(memoFactorial(10)).toEqual(factorial(10))
|
||||
expect(memoFactorial(10)).toEqual(3628800)
|
||||
})
|
||||
|
||||
it('expects the multipleFactorials function to use the cache on the second call', () => {
|
||||
const memoMultipleFactorials = memoize(multipleFactorials)
|
||||
const input = [2, 3, 4, 5]
|
||||
|
||||
expect(memoMultipleFactorials(input)).toEqual([2, 6, 24, 120])
|
||||
expect(memoMultipleFactorials(input)).toEqual(multipleFactorials(input))
|
||||
})
|
||||
|
||||
it('expects the multipleFactorials function to use the cache on the second call', () => {
|
||||
const memoMultipleFactorials = memoize(multipleFactorials)
|
||||
const input = [2, 3, 4, 5]
|
||||
|
||||
expect(memoMultipleFactorials(input)).toEqual([2, 6, 24, 120])
|
||||
expect(memoMultipleFactorials(input)).toEqual(multipleFactorials(input))
|
||||
})
|
||||
|
||||
it('expects the union function to use the cache on the second call', () => {
|
||||
const memoUnion = memoize(union)
|
||||
const inputs = [
|
||||
new Set([1, 2, 3]),
|
||||
new Set([4, 3, 2]),
|
||||
new Set([5, 3, 6])
|
||||
]
|
||||
|
||||
expect(memoUnion(...inputs)).toEqual(new Set([1, 2, 3, 4, 5, 6]))
|
||||
expect(memoUnion(...inputs)).toEqual(union(...inputs))
|
||||
})
|
||||
})
|
||||
|
Reference in New Issue
Block a user