Skip to content

Instantly share code, notes, and snippets.

@marekdano
Created October 12, 2020 21:43
Show Gist options
  • Save marekdano/d2eb3bfbe7a5760c389436a594ea195a to your computer and use it in GitHub Desktop.
Save marekdano/d2eb3bfbe7a5760c389436a594ea195a to your computer and use it in GitHub Desktop.
const factorial = num => (num > 1 ? num * factorial(num - 1) : 1)
const memoize = fn => {
const cache = {}
// with multiple arguments
// return (...args) => {
// const key = JSON.stringify(args)
// return key in cache ? cache[key] : cache[key] = fn.apply(null, args)
// }
return num => num in cache ? cache[num] : cache[num] = fn(num)
}
const memoizedFactorial = memoize(factorial)
console.log(`factorial(7)=${factorial(7)}`)
console.log(`factorial(4)=${factorial(4)}`)
console.log(`factorial(7)=${factorial(7)}`)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment