Last active
August 25, 2020 00:24
-
-
Save ajmas/d916cb6c5b77b1aa920d0d18f193a3ba to your computer and use it in GitHub Desktop.
JS Date Utilities
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Given an array of days of week, return in how many days the | |
* next candidate day is. If no candidate is found, then -1 is | |
* returned, since delta is always positive and non-zero. | |
* | |
* The following chart expresses the logic, where 'X' represents | |
* the `dayOfWeek` and `daysOfWeek` represent the days of next | |
* possible occurrence. | |
* | |
* ``` | |
* X 1 2 3 4 5 6 7 | |
* 1 D D => 3 .. +2 | |
* 1 D => 1 .. +1 | |
* 2 D => 4 .. +2 | |
* 2 D => 1 .. +6 | |
* 4 D => 4 .. +7 | |
* 4 D D => 1 .. +4 | |
* ``` | |
* | |
* @param dayOfWeek | |
* @param daysOfWeek | |
*/ | |
function getNextDayDelta(dayOfWeekNow: number, daysOfWeek: number[]) { | |
let selectedDelta = 8; | |
for (let i = 0; i < daysOfWeek.length; i++) { | |
const dayOfWeek = daysOfWeek[i]; | |
let nextDayDelta = dayOfWeek - dayOfWeekNow; | |
if (nextDayDelta === 0) { | |
// if same day, then it will be in week's time | |
nextDayDelta = 7; | |
} else if (nextDayDelta < 0) { | |
// if negative then we substract that value (7 + -delta) | |
nextDayDelta = 7 + nextDayDelta; | |
} | |
if (nextDayDelta < selectedDelta) { | |
selectedDelta = nextDayDelta; | |
} | |
} | |
if (selectedDelta < 8) { | |
return selectedDelta; | |
} | |
return -1; | |
} | |
console.log(getNextDayDelta(1, [1, 3])); | |
console.log(getNextDayDelta(1, [2])); | |
console.log(getNextDayDelta(2, [4])); | |
console.log(getNextDayDelta(2, [1])); | |
console.log(getNextDayDelta(4, [4])); | |
console.log(getNextDayDelta(4, [1, 4])); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment