jussi-kalliokoski / trine

A utility library for modern JavaScript.
ISC License
1.42k stars 35 forks source link

mathematical generators for trine? #51

Open nikhedonia opened 9 years ago

nikhedonia commented 9 years ago

recently i've started using trine (production code) for time-series visualisations and ended up writing some mathematical functions, for moving sum, average , variances, discrete differentiation, etc. any interests?

examples :


export function * sum ( N, cache=[] ) {
    if(N<=0){ return; }
    cache.fill(0,cache.length,N);
    let sum = cache.reduce((a,b)=>a+b,0);
    for(const value of this){
      sum+=value;
      sum-=cache.shift();
      cache.push(value);
      yield sum;
    }
}

export function * average( N, cache=[] ){
   yield * this::sum(N, cache )::map(function(){ return this/N; });
}

const sq = function(){return this*this;};

export function * variance ( N, cache=[] ) {
    let X  = this::map(sq)::sum( N, [...cache::map(sq)] );
    let Y  = this::sum( N, cache )::map(sq); 
    const N2= N*N;
    yield * [X,Y]::zip()::map(function(){
        return this[0]/N - this[1]/N2;
    });
}

// usage 
// [2,4,6,8]::sum(2)      // yields 2,6,10,14
// [2,4,6,8]::average(2)  // yields 1,3,5,7
// [2,4,6,8]::variance(2) // yields 1,1,1,1