Smoothing

by hoolymama

JavaScript

// A function to return a series of pairs, where the second element of
// each pair is a smoothed version of the first, with respect to it's neighbors.


const smooth = (series, neighbors) => {
  return series.map((value, i) => {
    let num = Math.min(neighbors, i)
    num = Math.min(num,series.length - (i + 1))
    
    let average = 0;
    for (j = i - num; j < i + num + 1; j++) {
      average += series[j];
    }
    
    average /= num * 2 + 1;
    return [value, average];
  });
};


// Run the smooth function and log the results
smooth([1.5, 2, 7.8, 4.4, 4.4, 6, 5.7, 8.1, 8],  3).forEach(
    ([origval, newval]) => {
      console.log(`${origval} --- ${newval}`);
    }
  );