JavaScript solution using reduce


  • 0
    G
    var MovingAverage = function(size) {
        this.size = size;
        this.q = [];
    };
    
    MovingAverage.prototype.next = function(val) {
        this.q.push(val);
        while (this.q.length > this.size) this.q.shift();
        return this.q.reduce(function(a, b) {return a + b}, 0) / Math.min(this.size, this.q.length);
    };
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.