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

97.5% Statements 39/40
83.33% Branches 10/12
100% Functions 5/5
97.5% Lines 39/40

    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
    1×
    1×

    1×

    1×

    68×
    68×
    68×

    68×
    68×
    68×
    68×
    68×
    68×
    68×
    68×
    1185×

    607×
    607×

    578×
    578×
    578×

    1185×

    68×

    68×

    68×
    54×
    54×
    30×

    1×
    3×

    3×
    3×
    3×

    1×
    1×

    1×
    1131×
    1131×
    548×

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

    let SMA;

    module.exports = SMA = function(input) {

        var period = input.period;
        var price  = input.values;
        this.format = input.format || nf;

        this.generator = (function* (period){
            var list = new LinkedList();
            var sum = 0;
            var counter = 1;
            var current = yield;
            var result;
            list.push(0);
            while(true){
                if(counter < period){
                    counter ++;
                    list.push(current);
                    sum = sum + current;
                }
                else{
                    sum = sum - list.shift() + current;
                    result = ((sum) / period);
                    list.push(current);
                }
                current = yield result;
            }
        })(period);

        this.generator.next();

        this.result = [];

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

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

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

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