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

97.44% Statements 38/39
87.5% Branches 14/16
100% Functions 5/5
97.44% Lines 38/39

    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×

    24×
    24×
    24×
    24×
    24×

    24×

    24×

    24×
    24×
    24×
    24×
    747×
    456×
    456×

    291×
    291×
    291×
    24×

    24×

    24×
    36×
    36×
    20×

    1×
    1×

    1×
    1×
    1×

    1×
    1×

    1×
    711×
    711×
    460×

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

    let EMA;

    module.exports = EMA = function(input) {

        var period = input.period
        var priceArray = input.values;
        var exponent = (2 / (period + 1));
        var sma;
        this.format = input.format || nf;

        this.result = [];

        sma = new SMA({period : period, values :[]});

        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));
            }
        });
    };

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

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

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