Created
          December 19, 2021 10:13 
        
      - 
      
- 
        Save shawn-dsz/a26d187ab8ba9162706a89a48a4444b4 to your computer and use it in GitHub Desktop. 
    create memoize function
  
        
  
    
      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 createHash = (item) => JSON.stringify(item); | |
| const memoize = (original) => { | |
| const cache = {}; | |
| return (...args) => { | |
| const hash = createHash(args); | |
| if (cache.hasOwnProperty(hash)) { | |
| return cache[hash]; | |
| } | |
| cache[hash] = original(...args); | |
| return cache[hash]; | |
| }; | |
| }; | |
| const foo = (a, b, c) => { | |
| console.log(`I do some expensive computation with ${a}, ${b}, ${c}`); | |
| return a + b + c; | |
| }; | |
| const memoizedFoo = memoize(foo); | |
| console.log(memoizedFoo(1, 2, 3)); | |
| console.log(memoizedFoo(2, 5, 6)); | |
| console.log(memoizedFoo(1, 2, 3)); | |
| console.log(memoizedFoo(2, 5, 6)); | 
  
    Sign up for free
    to join this conversation on GitHub.
    Already have an account?
    Sign in to comment