I need to fill missing business days (i.e. any days except saturday and sunday) in a series. So let's say I have this array:
const arr = [
"Date,Value",
"2020-12-31,1",
"2021-01-01,-3",
"2021-01-04,-38",
"2021-01-05,-14",
"2021-01-07,27",
"2021-01-08,55",
]
"2021-01-06" is a wednesday, but is missing in the array. What I need to do then is to take the value from the day before (-14) and use it for "2021-01-06". At the end it would look like this:
[
"Date,Value",
"2020-12-31,1",
"2021-01-01,-3",
"2021-01-04,-38",
"2021-01-05,-14",
"2021-01-06,-14",
"2021-01-07,27",
"2021-01-08,55",
]
Currently Im using this algorithm (which seems to work), but I wonder if it can be done more efficiently:
const fixEmptyBusinessDays = (arr) => {
const newArr = [];
if(arr.length){
newArr.push(arr[0]);
arr.shift();
let latestValue = 0;
for(let i = 0;i<arr.length;i++){
const el = arr[i];
if(el && el.length){
newArr.push(el);
if(el.length > 1){
const val = el[1];
latestValue = val;
}
const currDate = el[0];
const currDateAsDateObject = new Date(currDate);
if(currDate && currDateAsDateObject){
const day = currDateAsDateObject.getDay();
if((i+1)<arr.length && arr[i+1] && arr[i+1].length){
const next = arr[i+1];
const nextDayInFile = next[0];
const nextWeekDayUnformatted = get_next_weekday(new Date(currDate));
const nextMonth = (nextWeekDayUnformatted.getMonth()+1) < 10 ? `0${(nextWeekDayUnformatted.getMonth()+1)}` : (nextWeekDayUnformatted.getMonth()+1);
const nextDay = nextWeekDayUnformatted.getDate() < 10 ? `0${nextWeekDayUnformatted.getDate()}` : nextWeekDayUnformatted.getDate();
const nextWeekDay = `${nextWeekDayUnformatted.getFullYear()}-${nextMonth}-${nextDay}`
if(nextDayInFile !== nextWeekDay){
newArr.push([nextWeekDay, latestValue]);
}
}
}
}
}
}
return newArr;
}
const arr = [
"Date,Value",
"2020-12-31,1",
"2021-01-01,-3",
"2021-01-04,-38",
"2021-01-05,-14",
"2021-01-07,27",
"2021-01-08,55",
]
const result = fixEmptyBusinessDays(arr);