mirror of
https://github.com/alrayyes/wiki.git
synced 2024-11-22 11:36:23 +00:00
32 lines
428 B
Markdown
32 lines
428 B
Markdown
---
|
|
id: fdef5507-41d5-4510-b392-c1534f3def91
|
|
title: memoization
|
|
---
|
|
|
|
# Origin
|
|
|
|
Latin for "mindful remembering"
|
|
|
|
# Description
|
|
|
|
Cache the return value of a function
|
|
|
|
# Example
|
|
|
|
``` javascript
|
|
const memo = {}
|
|
|
|
function fib(n) {
|
|
if(memo[n]) {
|
|
return memo[n]
|
|
}
|
|
if(n <= 1) {
|
|
return 1
|
|
}
|
|
|
|
return memo[n] = fib(n -1) + fib(n - 2)
|
|
}
|
|
|
|
fib(5)
|
|
console.log(memo) // { '2': 2, '3': 3, '4': 5, '5': 8 }
|
|
```
|