# All files / src/utils ewma.ts

100% Statements 12/12
100% Branches 4/4
100% Functions 4/4
100% Lines 12/12

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

    30x

    10x
    10x
    10x

    18x
    18x
    18x

    10x

    18x
    12x
    12x

    6x

     /*
     * compute an Exponential Weighted moving average
     * - https://en.wikipedia.org/wiki/Moving_average#Exponential_moving_average
     *  - heavily inspired from shaka-player
     */

    class EWMA {
      private alpha_: number;
      private estimate_: number;
      private totalWeight_: number;

      //  About half of the estimated value will be from the last |halfLife| samples by weight.
      constructor (halfLife: number) {
        // Larger values of alpha expire historical data more slowly.
        this.alpha_ = halfLife ? Math.exp(Math.log(0.5) / halfLife) : 0;
        this.estimate_ = 0;
        this.totalWeight_ = 0;
      }

      sample (weight: number, value: number) {
        let adjAlpha = Math.pow(this.alpha_, weight);
        this.estimate_ = value * (1 - adjAlpha) + adjAlpha * this.estimate_;
        this.totalWeight_ += weight;
      }

      getTotalWeight (): number {
        return this.totalWeight_;
      }

      getEstimate (): number {
        if (this.alpha_) {
          let zeroFactor = 1 - Math.pow(this.alpha_, this.totalWeight_);
          return this.estimate_ / zeroFactor;
        } else {
          return this.estimate_;
        }
      }
    }

    export default EWMA;