Skip to content

Instantly share code, notes, and snippets.

@harunorimurata
Last active October 7, 2024 12:09
Show Gist options
  • Save harunorimurata/3e1a9aef976782fbe363982c21da2e70 to your computer and use it in GitHub Desktop.
Save harunorimurata/3e1a9aef976782fbe363982c21da2e70 to your computer and use it in GitHub Desktop.
const memoize = (func) => {
const memo = new Map()
return (...args) => {
const key = JSON.stringify(args)
if (!memo.has(key)) memo.set(key, func(...args))
return memo.get(key)
}
}
/*
const factorial = memoize((n) => {
if (n === 0) return 1
return n * factorial(n - 1)
})
factorial(5)
factorial(6)
const fibonacci = memoize((n) => {
if (n < 1) return 0
if (n === 1) return 1
return fibonacci(n - 2) + fibonacci(n - 1)
})
for (let i = 0; i < 21; i ++) {
console.log(fibonacci(i))
}
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment