I have a bit shift mask that represents days in a week:
Sunday = 1
Monday = 2
Tuesday = 4
...
Saturday = 64
I'm using a bitmask because several (at least one) days may be set to 1.
The problem
Then I get a date. Any date. And based on the date.DayOfWeek
I need to return the first nearest date after it that is set in the bitmask. So my method can return the same day or any other day between date
and date + 6
.
Example 1
My bitmask defines all days being set to 1. In this case my method should return the same date, because date.DayOfWeek
is set in the bitmask.
Example 2
My bitmask defines that only Wednesday is set to 1. If my incoming date is Tuesday, I should return date+1
(which is Wednesday). But if incoming date is Thursday I should return date+6
(which is again Wednesday).
Question
What is the fastest and most elegant way of solving this? Why also fastest? Because I need to run this several times so if I can use some sort of a cached structure to get dates faster it would be preferred.
Can you suggest some guidance to solve this in an elegant way? I don't want to end up with a long spaghetti code full of ifs and switch-case statements...
Important: It's important to note that bitmask may be changed or replaced by something else if it aids better performance and simplicity of code. So bitmask is not set in stone...
A possible approach
It would be smart to generate an array of offsets per day and save it in a private class variable. Generate it once and reuse it afterwards like:
return date.AddDays(cachedDayOffsets[date.DayOfWeek]);
This way we don't use bitmask at all and the only problem is how to generate the array the fastest and with as short code as possible.