mirror of
https://github.com/TheAlgorithms/JavaScript.git
synced 2025-07-05 08:16:50 +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
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user