/day-calculator.js Secret
Last active
October 5, 2016 04:20
-
-
Save DaneSirois/cafd43247f749d73a25da8af8aa0f6d7 to your computer and use it in GitHub Desktop.
W1D2 - Debugging incorrect code
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
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