function weightedAverageRoutine(x_n, offset) { // The number of samples to average is equal to the number of taps in the filter's // impulse response var Taps = filterTapsGenerator(); var N = Taps.length; // Calculate the position of the first sample in the window var start = offset - N; if (start < 0) { // Until enough samples have been received, no average can be calculated var Y_n = NaN; } else { // Initialize Y_n to 0 var Y_n = 0; // Once enough samples have been received, calculate the weighted average of all // the samples in the window for (var i=0; i<N; i++) { // The signal samples within the window are multiplied by the corresponding // filter tap Y_n += x_n[i+start] * Taps[i]; } } // Return the moving average return Y_n; }