Skip to content

Instantly share code, notes, and snippets.

@sahibalejandro
Created August 31, 2019 08:20
Show Gist options
  • Save sahibalejandro/7a38bd00589eaf6da2b99d0e66217c7a to your computer and use it in GitHub Desktop.
Save sahibalejandro/7a38bd00589eaf6da2b99d0e66217c7a to your computer and use it in GitHub Desktop.
Business Time Challenge
function addBusinessTime(holiday, time, duration) {
let finalTime = new Date(time.getTime());
finalTime.setSeconds(finalTime.getSeconds() + duration);
// First lets cover all possible cases when the start time is before the
// holiday start.
if (time.getTime() <= holiday.start.getTime()) {
// If duration is negative or final time still before the holiday starts
// then there is nothing to do, simply return the final time.
if (duration <= 0 || (finalTime.getTime() <= holiday.start.getTime())) {
return finalTime;
}
// Ok... final time is after the holiday starts, we have to calculate
// the new final time by skipping the holiday.
const extraTime = finalTime.getTime() - holiday.start.getTime();
return new Date(holiday.end.getTime() + extraTime);
}
// This block covers all the possible cases where the start time is during
// the holiday.
if (time.getTime() >= holiday.start.getTime() && time.getTime() <= holiday.end.getTime()) {
// When duration is positive the new start time is the holiday end,
// otherwise, it is the holiday start, then we add the duration.
finalTime = new Date(duration >= 0 ? holiday.end.getTime() : holiday.start.getTime());
finalTime.setSeconds(finalTime.getSeconds() + duration);
return finalTime;
}
// At this point we know the start time is after the holiday...
// If duration is positive or the final time is after the holiday end we
// can return the final time.
if (duration >= 0 || (finalTime.getTime() >= holiday.end.getTime())) {
return finalTime;
}
// Finally... we know start time is after the holiday and final time
// is before or during the holiday, in this case we need to calculate
// the final time by skipping the holiday.
const difference = finalTime.getTime() - holiday.end.getTime();
return new Date(holiday.start.getTime() + difference);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment