Created
          December 21, 2017 17:09 
        
      - 
      
- 
        Save myrdd/958fe8548b73fa9cc715dc701b2ca11c to your computer and use it in GitHub Desktop. 
    MapBuilder
  
        
  
    
      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 IMapValueFactory<K, T> { | |
| construct: (key: K) => T; | |
| } | |
| interface IMapBuilder<K, T> { | |
| maybeConstruct: (key: K) => void; | |
| get: ( | |
| ((key: K, maybeConstruct?: boolean) => T | undefined) & | |
| ((key: K, maybeConstruct: true) => T) | |
| ); | |
| } | |
| class MapBuilder<K, T> extends Map<K, T> implements IMapBuilder<K, T> { | |
| private valueFactory: IMapValueFactory<K, T>; | |
| constructor(valueFactory: IMapValueFactory<K, T>) { | |
| super(); | |
| this.valueFactory = valueFactory; | |
| } | |
| public maybeConstruct(key: K) { | |
| if (!this.has(key)) { | |
| this.set(key, this.valueFactory.construct(key)); | |
| } | |
| } | |
| public get(key: K, maybeConstruct: boolean = false) { | |
| if (maybeConstruct) this.maybeConstruct(key); | |
| return super.get(key); | |
| } | |
| } | 
  
    Sign up for free
    to join this conversation on GitHub.
    Already have an account?
    Sign in to comment