mirror of
https://github.com/TheAlgorithms/JavaScript.git
synced 2025-07-06 01:18:23 +08:00
Added comments about memoization
This commit is contained in:
@ -1,21 +1,40 @@
|
|||||||
/**
|
/**
|
||||||
* Memoize
|
* Memoize
|
||||||
* @param {Function} fn
|
*
|
||||||
* @returns
|
* From [Wikipedia](https://en.wikipedia.org/wiki/Memoization),
|
||||||
|
* memoization is an optimization technique
|
||||||
|
* used primarily to speed up computer programs,
|
||||||
|
* by storing the results of expensive function calls
|
||||||
|
* and returning the cached result when the same inputs occur again
|
||||||
|
*
|
||||||
|
* This function is a first class objects,
|
||||||
|
* which lets us use it as [Higher-Order Function](https://eloquentjavascript.net/05_higher_order.html)
|
||||||
|
* and return another function
|
||||||
|
*
|
||||||
|
* @param {Function} func Original function
|
||||||
|
* @returns {Function} Memoized function
|
||||||
*/
|
*/
|
||||||
export const memoize = (func) => {
|
export const memoize = (func) => {
|
||||||
// Initializing new cache
|
// Initialization of a slot to store the function result
|
||||||
const cache = {}
|
const cache = {}
|
||||||
|
|
||||||
return (...args) => {
|
return (...args) => {
|
||||||
|
// Retrieving the first argument of the function
|
||||||
const [arg] = args
|
const [arg] = args
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Checks if the argument is already present in the cache,
|
||||||
|
* then return the associated value / result
|
||||||
|
*/
|
||||||
if (arg in cache) {
|
if (arg in cache) {
|
||||||
// Reading cache by argument
|
|
||||||
return cache[arg]
|
return cache[arg]
|
||||||
}
|
}
|
||||||
|
|
||||||
// Updating cache by argument
|
/**
|
||||||
|
* If the argument is not yet present in the cache,
|
||||||
|
* execute original function and save its value / result in cache,
|
||||||
|
* finally return it
|
||||||
|
*/
|
||||||
const result = func(arg)
|
const result = func(arg)
|
||||||
cache[arg] = result
|
cache[arg] = result
|
||||||
return result
|
return result
|
||||||
|
Reference in New Issue
Block a user