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:
Fahim Faisaal
2022-03-02 14:56:16 +06:00
committed by GitHub
parent eb748ae78d
commit 6656ece534
2 changed files with 72 additions and 27 deletions

View File

@ -1,33 +1,48 @@
/** /**
* Memoize * @function memoize
* * @description ->
* From [Wikipedia](https://en.wikipedia.org/wiki/Memoization), * From [Wikipedia](https://en.wikipedia.org/wiki/Memoization),
* memoization is an optimization technique * memoization is an optimization technique
* used primarily to speed up computer programs, * used primarily to speed up computer programs,
* by storing the results of expensive function calls * by storing the results of expensive function calls
* and returning the cached result when the same inputs occur again * and returning the cached result when the same inputs occur again
*
* This function is a first class objects, * This function is a first class objects,
* which lets us use it as [Higher-Order Function](https://eloquentjavascript.net/05_higher_order.html) * which lets us use it as [Higher-Order Function](https://eloquentjavascript.net/05_higher_order.html)
* and return another function * and return another function
*
* @param {Function} func Original function * @param {Function} func Original function
* @returns {Function} Memoized function * @returns {Function} Memoized function
*/ */
export const memoize = (func) => { const memoize = (func) => {
// Initialization of a slot to store the function result // Initialization of a slot to store the function result by arguments as a key in Hash Map
const cache = {} const 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]
}
if (value instanceof Map) { // if the value is Map it's converted to Object cause JSON.stringify can't convert Map
return Object.fromEntries(value)
}
return value
}
return (...args) => { return (...args) => {
// Retrieving the first argument of the function /**
const [arg] = args * Arguments converted to JSON string for use as a key of Map - it's easy to detect collections like -> Object and Array
* If the args input is -> [new Set([1, 2, 3, 4]), {name: 'myName', age: 23}]
* Then the agrsKey generate to -> '[[1,2,3,4],{"name":"myName","age":23}]' which is JSON mean string
* Now it's ready to be a perfect key for Map
*/
const argsKey = JSON.stringify(args, jsonReplacer)
/** /**
* Checks if the argument is already present in the cache, * Checks if the argument is already present in the cache,
* then return the associated value / result * then return the associated value / result
*/ */
if (arg in cache) { if (cache.has(argsKey)) {
return cache[arg] return cache.get(argsKey)
} }
/** /**
@ -35,8 +50,11 @@ export const memoize = (func) => {
* execute original function and save its value / result in cache, * execute original function and save its value / result in cache,
* finally return it * finally return it
*/ */
const result = func(arg) const result = func(...args) // spread all args
cache[arg] = result cache.set(argsKey, result)
return result return result
} }
} }
export { memoize }

View File

@ -1,22 +1,21 @@
import { memoize } from '../Memoize' import { memoize } from '../Memoize'
import { fibonacci } from '../../Dynamic-Programming/FibonacciNumber'
import { factorial } from '../../Recursive/Factorial'
const fibonacci = (n) => { const multipleFactorials = (arr) => arr.map(factorial)
if (n < 2) {
return n
}
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) => { describe('Testing Memoize', () => {
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', () => { it('expects the fibonacci function to use the cache on the second call', () => {
const memoFibonacci = memoize(fibonacci) const memoFibonacci = memoize(fibonacci)
@ -34,4 +33,32 @@ describe('Memoize', () => {
expect(memoFactorial(10)).toEqual(factorial(10)) expect(memoFactorial(10)).toEqual(factorial(10))
expect(memoFactorial(10)).toEqual(3628800) 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))
})
}) })