/*
Let's break down the function step by step:
1. We define the `movingAverage` function that takes a list of data as input.
2. We initialize the window size to 10 seconds and two empty lists to store the data in the window and the moving average results.
3. We loop through each datapoint in the data list and extract its timestamp and value.
4. We remove datapoints from the window that are more than 10 seconds old by comparing their timestamp with the current datapoint timestamp minus 10 seconds.
5. We append the current datapoint to the window.
6. We calculate the moving average for the current window by adding up the values of all datapoints in the window and dividing by the number of datapoints.
7. We append the timestamp of the current datapoint and the moving average to the result list.
8. We return the result list.
*/
function moving_Average(data) {
const windowSize = 10; // 10 seconds window
let win = []; // Intermediate array
let res = []; // array to store the moving average
// We will loop through each datapoint in the data
data.forEach(point => {
const time = new Date(point[0]);
const value = point[1];
// We will remove datapoints that are more than 10 seconds old from the window
while (win.length > 0 && win[0][0] < new Date(time - windowSize * 1000)) {
win.shift();
}
// Here we will append the new datapoint to the window
win.push([time, value]);
// calculate the moving average for the current window
if (win.length > 0) {
const total = win.reduce((sum, point) => sum + point[1], 0);
const avg = total / win.length;
res.push([point[0], avg]);
}
});
return res;
}
// Sample data
const data = [
['2021-01-01 00:00:00', 2],
['2021-01-01 00:00:02', 3],
['2021-01-01 00:00:03', 4],
['2021-01-01 00:00:04', 5],
['2021-01-01 00:00:05', 6],
['2021-01-01 00:00:13', 10],
['2021-01-01 00:00:14', 14],
['2021-01-01 00:00:15', 12],
['2021-01-01 00:00:16', 13],
['2021-01-01 00:00:18', 14],
];
const result = moving_Average(data);
result.forEach(point => console.log(point));