Skip to content

Instantly share code, notes, and snippets.

@potatowave
Forked from DaneSirois/day-calculator.js
Created October 5, 2016 04:20
Show Gist options
  • Save potatowave/14560092c7192a2f4c33f208393d3046 to your computer and use it in GitHub Desktop.
Save potatowave/14560092c7192a2f4c33f208393d3046 to your computer and use it in GitHub Desktop.
W1D2 - Debugging incorrect code
var date = process.argv[2];
if (!date) {
console.log("Please provide a date in the format YYYY/MM/DD");
} else {
calculateDayInYear(date);
}
function calculateDayInYear(date) {
var splitDate = date.split('/');
var year = Number(splitDate[0]);
var month = Number(splitDate[1]);
var day = Number(splitDate[2]);
//console.log(year + " " + month + " " + day)
var febDays = daysInFeb(year);
var DAYS_IN_MONTH = [31, febDays, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
//console.log(DAYS_IN_MONTH);
if (year && validMonth(month) && validDay(month, day)) {
console.log(date, "is day", calculateDayNumber(month, day), "of the year", year);
} else {
console.log("Invalid date");
}
function validMonth(month) {
if (month && month >= 1 && month <= 12) {
return true;
} else {
return false;
}
}
function validDay(month, day) {
return day && day >= 1 && day <= DAYS_IN_MONTH[month - 1];
}
function calculateDayNumber(month, day) {
var dayOfYear = 0;
for (var i = 1; i <= month; i++) {
dayOfYear += DAYS_IN_MONTH[i - 1];
}
return dayOfYear;
}
function daysInFeb(year) {
if (isLeapYear(year)) {
return 29;
} else {
return 28;
}
}
function isLeapYear(year) {
return isMultiple(year, 400) || !isMultiple(year, 100) && isMultiple(year, 4);
}
}
function isMultiple(numerator, denominator) {
return numerator % denominator === 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment