Function movingAverage

Creates a moving average for a set number of samples. It returns a function which in turn yields an average value.

Moving average are useful for computing the average over a recent set of numbers. A lower number of samples produces a computed value that is lower-latency yet more jittery. A higher number of samples produces a smoother computed value which takes longer to respond to changes in data.

Sample size is considered with respect to the level of latency/smoothness trade-off, and also the rate at which new data is added to the moving average.

import { movingAverage } from 'https://unpkg.com/ixfx/dist/data.js';

const ma = movingAverage(10);
ma(10); // 10
ma(5); // 7.5

A weighting function can be provided to shape how the average is calculated - eg privileging the most recent data over older data. It uses Arrays.averageWeighted under the hood.

import { movingAverage } from 'https://unpkg.com/ixfx/dist/data.js';
import { gaussian } from 'https://unpkg.com/ixfx/dist/modulation.js';

// Give more weight to data in middle of sampling window
const ma = movingAverage(100, gaussian());

Because it keeps track of samples previous data, there is a memory impact. A lighter version is movingAverageLight which does not keep a buffer of prior data, but can't be as easily fine-tuned.

  • Parameters

    • samples: number = 100

      Number of samples to compute average from

    • Optionalweighter: ((v: number) => number)

      Optional weighting function

        • (v): number
        • Parameters

          • v: number

          Returns number

    Returns ((value?: number) => number)

      • (value?): number
      • Parameters

        • Optionalvalue: number

        Returns number