mirror of
https://github.com/TheAlgorithms/JavaScript.git
synced 2025-07-19 01:55:51 +08:00
24 lines
387 B
JavaScript
24 lines
387 B
JavaScript
/**
|
|
* Memoize
|
|
* @param {Function} fn
|
|
* @returns
|
|
*/
|
|
export const memoize = (func) => {
|
|
// Initializing new cache
|
|
const cache = {}
|
|
|
|
return (...args) => {
|
|
const [arg] = args
|
|
|
|
if (arg in cache) {
|
|
// Reading cache by argument
|
|
return cache[arg]
|
|
}
|
|
|
|
// Updating cache by argument
|
|
const result = func(arg)
|
|
cache[arg] = result
|
|
return result
|
|
}
|
|
}
|