What is Memoization?

function square(n) {
let result = 0
for (let i = 1; i <= n; i++) {
for (let j = 1; j <= n; j++) {
result +=1
}
}
return result
}
const previousResults = []function square(n) {
let result = 0
for (let i = 1; i < n; i++ {
for (let j = 1; j < n; j++ {
result +=1
}
}
previousResults[n] = result
return result
}
const previousResults = []function square(n) {
if (previousResults[n] != null) {
return previousValues[n]
}
let result = 0
for (let i = 1; i < n; i++ {
for (let j = 1; j < n; j++ {
result +=1
}
}
previousResults[n] = result
return result
}
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, ...]
function fib(n) {
if (n < 2) {
return n
}
return fib(n - 1) fib(n - 2)
}
function memoize(fn) {
previousValues = {}
return function(...args) {
if (previousValues[args] {
return previousValues[args]
}
const result = fn.apply(this)
previousValues[args] = result
return result
}
function fib(n) {
if (n < 2) {
return n
}
return fib(n - 1) fib(n - 2)
}
fib = memoize(fib)

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store