My raw data has values on some random times:
const rawData = [
{hour: 3, value: 3} ,
{hour: 5, value: 9} ,
{hour: 10, value: 5} ,
] as const
I would like to fill all missing hours as having value 0:
const processedData = [
{ hour: 3, value: 3 },
{ hour: 4, value: 0 },
{ hour: 5, value: 9 },
{ hour: 6, value: 0 },
{ hour: 7, value: 0 },
{ hour: 8, value: 0 },
{ hour: 9, value: 0 },
{ hour: 10, value: 5 }
]
Here is my code:
function fillEmptyData(data: typeof rawData) {
const processedData = []
for (const iString in data) {
const i = parseInt(iString)
processedData.push(data[i])
if (data[i+1]===undefined || data[i].hour + 1 === data[i+1].hour) {
continue
} else {
const currentHour = data[i].hour
const nextAvailableHour = data[i+1].hour
const gap = nextAvailableHour - currentHour
const emptyHours = Array(gap-1).fill().map((_, i) => i+currentHour+1)
for (const emptyHour of emptyHours) {
processedData.push({
hour: emptyHour,
value: 0
})
}
}
}
return processedData
}
console.log(fillEmptyData(rawData))
Is there anything in this code that may be improved?