Created
          July 5, 2018 12:30 
        
      - 
      
- 
        Save farskid/4602a9dc35188d889d171e0163d82754 to your computer and use it in GitHub Desktop. 
    Memoize functions in Javascript
  
        
  
    
      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 cache = {}; | |
| function memoizedFunc (...args) { | |
| const hash = JSON.stringify(args); | |
| if (cahce.hasOwnProperty(hash)) { | |
| return cache[hash]; | |
| } | |
| const newValue = fn(...args); | |
| cache[hash] = newValue; | |
| return newValue; | |
| } | |
| memoizedFunc.clear = function() { | |
| cache = {}; | |
| } | |
| return memoizedFunc; | |
| } | |
| const add = (a, b) => a + b; | |
| const memoizedAdd = memoize(add); | |
| memoizedAdd(1,1); // new calculation | |
| memoizedAdd(1,1); // cache | |
| memoizedAdd(1,1); // cache | |
| memoizedAdd.clear(); | |
| memoizedAdd(1,1); // new calculation | 
  
    
      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
    
  
  
    
  | interface IMemoizedFunc { | |
| (...args: any[]): any; | |
| clear: () => void; | |
| } | |
| function memoize(fn) { | |
| let cache: {string?: any} = {}; | |
| const memoizedFunc = <IMemoizedFunc>function(...args) { | |
| const hash = JSON.stringify(args); | |
| if (cahce.hasOwnProperty(hash)) { | |
| return cache[hash]; | |
| } | |
| const newValue = fn(...args); | |
| cache[hash] = newValue; | |
| return newValue; | |
| } | |
| memoizedFunc.clear = function() { | |
| cache = {}; | |
| } | |
| return memoizedFunc; | |
| } | |
| const add = (a, b) => a + b; | |
| const memoizedAdd = memoize(add); | |
| memoizedAdd(1,1); // new calculation | |
| memoizedAdd(1,1); // cache | |
| memoizedAdd(1,1); // cache | |
| memoizedAdd.clear(); | |
| memoizedAdd(1,1); // new calculation | 
  
    Sign up for free
    to join this conversation on GitHub.
    Already have an account?
    Sign in to comment