Javascript Array simpleSMA(N)

Description

Javascript Array simpleSMA(N)


// single-sided/*from   www  .  ja v  a2  s.  com*/
Array.prototype.simpleSMA=function(N) {
return this.map(function(x,i,v) {
    if(i<N-1) return NaN;
    return v.filter(function(x2,i2) { return i2<=i && i2>i-N; }).reduce(function(a,b){ return a+b; })/N;
}); };

g=[1,2,3,4,5,8,5,4];
console.log(g.simpleSMA(3))
console.log(g.simpleSMA(5))

Javascript Array simpleSMA(N)

// single-sided/*from ww w  .  j  a v  a 2s . c  om*/
Array.prototype.simpleSMA=function(N) {
return this.map(
  function(el,index, _arr) {
      return _arr.filter(
      function(x2,i2) {
        return i2 <= index && i2 > index - N;
        })
      .reduce(
      function(current, last, index, arr){
        return (current + last);
        })/index || 1;
      });
};

g=[0,1,2,3,4,5,6,7,8,9,10];
console.log(g.simpleSMA(3));
console.log(g.simpleSMA(5));
console.log(g.simpleSMA(g.length));



PreviousNext

Related