Last active
July 28, 2018 19:10
-
-
Save headquarters/f08274b00d0829c22caed8cf8bac4755 to your computer and use it in GitHub Desktop.
Memoization in JavaScript using ES6 structures
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
| function memoize(fn) { | |
| let state = {}; | |
| return function() { | |
| const args = [...arguments]; | |
| if(state[args]) { | |
| return state[args]; | |
| } else { | |
| const value = fn.apply(this, args); | |
| state[args] = value; | |
| return value; | |
| } | |
| } | |
| } | |
| function add(a, b) { | |
| console.log('adding', a, b); | |
| return a + b; | |
| } | |
| const memoizedAdd = memoize(add); | |
| console.log(memoizedAdd(1, 2)); | |
| // adding 1 2 | |
| // 3 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment