# all files / technicalindicators/lib/indicator/ indicator.js

0% Statements 0/43
0% Branches 0/16
0% Functions 0/8
0% Lines 0/42

    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
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77

     "use strict"
    const SMA        = require('./SMA');
    const nf         = require('../Utils/NumberFormatter');

    let EMA;

    module.exports = EMA = class EMA {
      constructor(input) {
        this._generate(input);
      };

      _generate(input) {
        var period;
        var priceArray;
        var exponent;
        var sma;
        this.format = input.format || nf;
        this.result = [];
        period = input.period;
        exponent = (2 / (period + 1));
        priceArray = input.values;
        sma = new SMA({period : period, values :[], format : (v) => {return v}});

        this.generator = (function* (){
          var tick;
          var prevEma;
          while (true) {
            if(prevEma && tick){
              prevEma = ((tick - prevEma) * exponent) + prevEma;
              tick = yield prevEma;
            }else {
              tick = yield;
              prevEma = sma.nextValue(tick)
              if(prevEma)
                tick = yield prevEma;
            }
          }
        })();

        this.generator.next();

        priceArray.forEach((tick) => {
          var result = this.generator.next(tick);
          if(result.value){
            this.result.push(this.format(result.value));
          }
        });
      }

      static calculate(){
        if(input.reversedInput) {
          input.values.reverse();
        }
        let result = (new EMA(input)).result;
        input.reversedInput ? result.reverse():undefined;
        return result;
      }

      set result(result) {
        this.result = result;
      }

      get result() {
        return this.result;
      }

      getResult() {
        return this.result;
      }

      nextValue(input)  {
        var nextResult = this.generator.next(input);
        if(nextResult.value)
          return this.format(nextResult.value);
      }
    }