Last active
April 5, 2018 03:09
-
-
Save luzeduardo/f8acb1930310834c15f6d74d21a678b9 to your computer and use it in GitHub Desktop.
memoization.js
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 mem = (fn) => { | |
| const cache = {} | |
| return (...args) => { | |
| if (cache[args]) { | |
| return cache[args] | |
| } | |
| const res = fn.apply(this, args) | |
| cache[args] = res | |
| return res | |
| } | |
| } | |
| function slowFib(n) { | |
| if (n < 2) { | |
| return n | |
| } | |
| return fib(n - 1) + fib(n - 2) | |
| } | |
| const fib = mem(slowFib) | |
| export default fib |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment