Skip to content

Instantly share code, notes, and snippets.

@ernestlv
Last active February 21, 2018 15:45
Show Gist options
  • Save ernestlv/6b33ecd64e927f010d2276c53d030327 to your computer and use it in GitHub Desktop.
Save ernestlv/6b33ecd64e927f010d2276c53d030327 to your computer and use it in GitHub Desktop.
calculate # of weeks you can spend in a trip given that you have two months vacations, starting on the 1st day of the first month and finishing on the last day of the second month. you can leave only on mondays and returns only on sundays
function solution(Y, A, B, W) {
// write your code in JavaScript (Node.js 8.9.4)
const MONTH_DAYS = {
"January":31, "February":28, "March":31, "April":30, "May":31, "June":30, "July":31, "August":31, "September":30, "October":31, "November":30, "December":31
};
const MONTHS = {
"January":0, "February":1, "March":2, "April":3, "May":4, "June":5, "July":6, "August":7, "September":8, "October":9, "November":10, "December":11
};
function findFirstVacationMonday(year, month) {
let monday = new Date(year, MONTHS[month], 1, 0, 0, 0, 0);
while(monday.getDay() !== 1){
monday.setDate(monday.getDate()+1);
}
return monday;
}
function findLastVacationSunday(year, month) {
let lastDayOfMonth = MONTH_DAYS[month];
if (month === "February") {
if (year % 4 === 0) {
lastDayOfMonth++;
}
}
let sunday = new Date(year, MONTHS[month], lastDayOfMonth, 0, 0, 0, 0);
while(sunday.getDay() !== 0){
sunday.setDate(sunday.getDate()-1);
}
return sunday;
}
function countDays(firstMonday, lastSunday) {
return Math.round((lastSunday - firstMonday) / (24 * 60 * 60 * 1000))+1
}
let monday = findFirstVacationMonday(Y, A);
let sunday = findLastVacationSunday(Y, B);
return countDays(monday, sunday) / 7;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment