/**
* @typedef {Object} HoursData - Represents an entry containing hour-value data.
* @property {number} hour - The hour of the entry.
* @property {number} value - The value associated with the hour.
*/
/**
* Fills missing hours in a series of hour-value entries.
* @param {HoursData[]} hours - A series of hour-value entries sorted ascending by hour.
* @returns {HoursData[]} - A copy of the hours with gaps filled.
*/
const fillMissingHours = hours => {
const result = [];
let last;
for (const entry of hours) {
for (let i = last + 1; i < entry.hour; i++) {
result.push({hour: i, value: 0});
}
result.push({...entry});
last = entry.hour;
}
return result;
};
const rawData = [
{hour: 3, value: 3},
{hour: 5, value: 9},
{hour: 10, value: 5},
];
console.log(fillMissingHours(rawData));
I used JSDoc instead of TS so this is runnable in the browser, but I assume you have the TS types handled already.
Use standard formatting with Prettier (avoid smushed together expressions like
i+currentHour+1and extra spacing like{hour: 10, value: 5} ,).Avoid using the type in the variable namethe type in the variable name, so
iStringshould be named what it is only.igenerally means "index" so I'd avoid that in the name too.Your code only works when the input is pre-sorted. That's fine but needs to be documented as an invariant.
Don't use
into iterate arrays because it has gotchas you can read about in the docs. Preferfor ... of.Compute the final value once when possible. Consider these lines:
const gap = nextAvailableHour - currentHour const emptyHours = Array(gap-1)It's great that you've broken out a variable
gap, but since it's only used this one time, I'd compute its final value up front:const gap = nextAvailableHour - currentHour - 1 const emptyHours = Array(gap)This is a subtle distinction, but it's good practice to keep things in one place and be transparent about variables. Otherwise, the code reads like "The gap is nextAvailableHour - currentHour. Just kidding, it's actually - 1 that thing I just wrote on the previous line.".
Write a test suite to validate the logic thoroughly. This is the sort of function that can have a lot of edge cases. I was lazy and didn't test this, so if there's a bug, that only proves my point.
This actually isn't too bad, but you can probably see why I went forwith the simpler syntax in my recommendation.