# all files / technicalindicators/lib/Utils/ AverageLoss.js

78.05% Statements 32/41
72.73% Branches 16/22
60% Functions 3/5
78.05% Lines 32/41

    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

    1×

    1×

    1×

    4×
    4×
    4×

    4×
    4×
    4×
    4×
    4×
    4×
    4×
    4×
    88×
    88×
    88×
    32×

    88×

    32×
    4×

    28×

    88×
    88×
    88×

    4×

    4×

    4×

    1×

    1×

    1×
    88×

     /**
     * Created by AAravindan on 5/5/16.
     */
    "use strict"

    const nf  = require('../Utils/NumberFormatter');

    let AvgLoss;

    module.exports = AvgLoss = function(input) {

      let values = input.values;
      let period = input.period;
      let format = input.format || nf;

      this.generator = (function* (period){
        var currentValue = yield;
        var counter = 1;
        var lossSum = 0;
        var avgLoss;
        var loss;
        var lastValue;
        while(true){
          loss = lastValue ? (lastValue - currentValue) : 0;
          loss = loss ? loss : 0;
          if(loss > 0){
            lossSum = lossSum + loss;
          }
          if(counter < (period + 1)){
            counter++;
          }
          else if(!avgLoss){
            avgLoss = lossSum / period;
          }else {
            avgLoss = ((avgLoss * (period-1)) + (loss > 0 ? loss : 0))/period;
          }
          lastValue = currentValue;
          avgLoss = avgLoss ? format(avgLoss) : undefined;
          currentValue = yield avgLoss;
        }
      })(period);

      this.generator.next();

      this.result = [];

      values.forEach((tick) => {
        var result = this.generator.next(tick);
        if(result.value !== undefined){
          this.result.push(result.value);
        }
      });
    };

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

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

    AvgLoss.prototype.nextValue = function (price) {
      return this.generator.next(price).value;
    };