# All files / utils MemoizedFunctionCache.ts

92.86% Statements 13/14
75% Branches 3/4
100% Functions 2/2
90.91% Lines 10/11

Press n or j to go to the next uncovered block, b, p or k for the previous block.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    462x

    2x
    10x

    2x
    746x
    24x

    746x

    746x

    746x

    2x
     import memoizeOne from 'memoize-one'

    /*
      Stores a cache of memoized functions which can be looked up by an arbitrary
      key. The memoized functions are instatiated lazily.

      Example:

      ```
      const f = () => {
        console.log('f called')

        return 2
      }

      const cache = new MemoizedFunctionCache()
      const fMemoized = cache.get('myKey', f)

      fMemoized() // logs "f called", returns 2
      fMemoized() // returns 2
      ```

    */
    export class MemoizedFunctionCache {
      private memoizedFunctions: {
        [key: string]: {memoized: Function; original: Function}
      } = {}

      public get<T extends (...args: any[]) => any>(key: string, fn: T): T {
        if (!this.memoizedFunctions[key]) {
          this.memoizedFunctions[key] = {
            memoized: memoizeOne(fn),
            original: fn,
          }
        }

        const {memoized, original} = this.memoizedFunctions[key]

        Iif (original !== fn) {
          throw new Error(`expected ${fn} but found ${original}`)
        }

        return memoized as T
      }
    }