Languages
[Edit]
EN

TypeScript - moving average

3 points
Created by:
Richard-Bevan
413

In this article, we would like to show how to calculate the moving average in TypeScript

Quick solution:

const calculateItemsSum = (data: number[], start: number, stop: number): number => {
    let sum = 0;
    for (let j = start; j < stop; ++j) {
        sum += data[j];
    }
    return sum;
};

const caculateMovingAverage = (data: number[], window: number): number[] => {
    const steps = data.length - window;
    const result = [];
    for (let i = 0; i < steps; ++i) {
        const sum = calculateItemsSum(data, i, i + window);
        result.push(sum / window);
    }
    return result;
};


// Usage example:

const data: number[] = [1, 2, 3, 4, 5, 6];
const average: number[] = caculateMovingAverage(data, 3);

console.log(average);  // [2, 3, 4]

Output:

[2, 3, 4]

Where:

  • window means a number of elements used to calculate the average during one step.

Note: the above solution has O(n^2) complexity.

 

Optimal solution example

The presented solution in this section has only O(n) complexity.

const caculateMovingAverage = (data: number[], window: number): number[] => {
    const result = [];
    if (data.length < window) {
        return result;
    }
    let sum = 0;
    for (let i = 0; i < window; ++i) {
        sum += data[i];
    }
    result.push(sum / window);
    const steps = data.length - window - 1;
    for (let i = 0; i < steps; ++i) {
        sum -= data[i];
        sum += data[i + window];
        result.push(sum / window);
    }
    return result;
};


// Usage example:

const data: number[] = [1, 2, 3, 4, 5, 6];
const average: number[] = caculateMovingAverage(data, 3);

console.log(average);  // [2, 3, 4]

Output:

[2, 3, 4]

Warning: the above solution uses -= and += operations on the sum constiable that makes numerical mistakes when we work on floating numbers - it is good to modify below source code and recompute sum once per some amount of iterations (amount may be selectes empiricaly).

 

See also

  1. JavaScript - moving average

References

  1. Moving average - Wikipedia

  2. Computational complexity - Wikipedia

Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join