# all files / technicalindicators/lib/moving_averages/ WEMA.js

75.68% Statements 28/37
41.67% Branches 5/12
60% Functions 3/5
75% Lines 27/36

    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

    1×
    1×

    1×

    1×

    3×
    3×
    3×
    3×

    3×

    3×

    3×
    3×
    3×
    3×
    90×
    42×

    48×

    90×
    90×

    3×

    3×

    1×

    1×

    1×
    90×
    90×
    51×

     "use strict"
    //TODO; THis is copied from EMA for checking if WEMA works correctly, we need to refactor if this works good.
    const SMA        = require('./SMA');
    const nf = require('./../Utils/NumberFormatter');

    let WEMA;

    module.exports = WEMA = function(input) {

      var period = input.period
      var priceArray = input.values;
      var sma;
      this.format = input.format || nf;

      this.result = [];

      sma = new SMA({period : period, values :[], format : (v) => {return v}});

      this.generator = (function* (){
        var tick = yield;
        var prevMa,currentMa;
        while (true) {
          if(prevMa === undefined){
            currentMa = sma.nextValue(tick);
          }else {
            currentMa = ((prevMa * (period - 1)) + tick) / period;
          }
          prevMa = currentMa;
          tick = yield currentMa;
        }
      })();

      this.generator.next();

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

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

    WEMA.prototype.getResult = function () {
      return this.result;
    };

    WEMA.prototype.nextValue = function (price) {
      var nextResult = this.generator.next(price);
      if(nextResult.value)
        return this.format(nextResult.value);
    };