I have an API endpoint returning time-series data, where all records with the measure being 0 - gaps, are ignored. It looks like:
[
{
"EventsStaging.timestamp.hour":"2022-07-31T20:00:00.000",
"EventsStaging.timestamp":"2022-07-31T20:00:00.000",
"EventsStaging.userCount":"1"
},
{
"EventsStaging.timestamp.hour":"2022-07-31T21:00:00.000",
"EventsStaging.timestamp":"2022-07-31T21:00:00.000",
"EventsStaging.userCount":"1"
},
{
"EventsStaging.timestamp.hour":"2022-08-01T04:00:00.000",
"EventsStaging.timestamp":"2022-08-01T04:00:00.000",
"EventsStaging.userCount":"1"
},
{
"EventsStaging.timestamp.hour":"2022-08-01T16:00:00.000",
"EventsStaging.timestamp":"2022-08-01T16:00:00.000",
"EventsStaging.userCount":"1"
},
...
]
I want to trasform my data on the client it has records where the value is 0 so we need to add records into gaps as:
[
{
"EventsStaging.timestamp.hour":"2022-07-31T20:00:00.000",
"EventsStaging.timestamp":"2022-07-31T20:00:00.000",
"EventsStaging.userCount":"1"
},
{
"EventsStaging.timestamp.hour":"2022-07-31T21:00:00.000",
"EventsStaging.timestamp":"2022-07-31T21:00:00.000",
"EventsStaging.userCount":"1"
},
{
"EventsStaging.timestamp.hour":"2022-07-31T22:00:00.000",
"EventsStaging.timestamp":"2022-07-31T22:00:00.000",
"EventsStaging.userCount":"0"
},
{
"EventsStaging.timestamp.hour":"2022-07-31T23:00:00.000",
"EventsStaging.timestamp":"2022-07-31T23:00:00.000",
"EventsStaging.userCount":"0"
},
{
"EventsStaging.timestamp.hour":"2022-08-01T00:00:00.000",
"EventsStaging.timestamp":"2022-08-01T00:00:00.000",
"EventsStaging.userCount":"0"
},
...
{
"EventsStaging.timestamp.hour":"2022-08-01T04:00:00.000",
"EventsStaging.timestamp":"2022-08-01T04:00:00.000",
"EventsStaging.userCount":"1"
},
...
]
I wrote the below to fill the gaps:
const fillMissingEntries = (series, granularity) => {
const step = granularity === 'hour' ? 60 * 60 * 1000 : 0;
const key = Object.keys(series[0])[0];
const countKey = Object.keys(series[0])[2];
return series.reduce((acc, entry) => {
const prev = acc[acc.length - 1] || {};
for (
let i = 1;
new Date(entry[key]) <
new Date(new Date(entry[key]).getTime() + step * i);
i++
) {
acc.push({
[key]: new Date(new Date(entry[key]).getTime() + step * i),
[countKey]: 0,
...prev
});
}
return acc;
}, []);
};
I want to call as const transformed = fillMissingEntries(data, 'hour');, and I understand that reduce should allow me to do this in a single pass, but something is wrong with my code.