Untitled
unknown
javascript
2 years ago
2.2 kB
1
Indexable
Never
/* 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 movingAverage(data) { const windowSize = 10; // 10 seconds window let window = []; // Intermediate array let result = []; // array to store the moving average // We will loop through each datapoint in the data data.forEach(point => { const timestamp = new Date(point[0]); const value = point[1]; // We will remove datapoints that are more than 10 seconds old from the window while (window.length > 0 && window[0][0] < new Date(timestamp - windowSize * 1000)) { window.shift(); } // Here we will append the new datapoint to the window window.push([timestamp, value]); // calculate the moving average for the current window if (window.length > 0) { const total = window.reduce((sum, point) => sum + point[1], 0); const avg = total / window.length; result.push([point[0], avg]); } }); return result; } // 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 = movingAverage(data); result.forEach(point => console.log(point));