Created
April 29, 2020 12:26
-
-
Save leonidkuznetsov18/e4b28907362fce5e4eaa65b26ade1832 to your computer and use it in GitHub Desktop.
simple 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 memoize = (fn) => { | |
| let cache = {}; | |
| const cacheFn = (...args) => { | |
| let key = JSON.stringify(args); | |
| if (key in cache) { | |
| return cache[key] | |
| } | |
| return (cache[key] = fn.call(null, ...args)); | |
| } | |
| return cacheFn; | |
| }; | |
| function double(number) { | |
| console.log('[double]', number); | |
| return number * 2; | |
| } | |
| const memoizedDouble = memoize(double); | |
| console.log(memoizedDouble(5)); | |
| console.log(memoizedDouble(5)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment