Created
October 12, 2020 21:43
-
-
Save marekdano/d2eb3bfbe7a5760c389436a594ea195a to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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