Self-made for-loop clean-up suggestions


#1

Hi everyone,

I created the following loop as practice, and it works just fine, but I'm wondering if anyone has any advice to clean it up. Thanks!

var leapyear = prompt("Is it a leap year?")
var daysofMonth = function() {
if (leapyear === "yes") {
return [31,29,31,30,31,30,31,31,30,31,30,31]
} else {
return [31,28,31,30,31,30,31,31,30,31,30,31]}
}
var todaysMonth = prompt("What is the month?")
var todaysDay = prompt("What is the day of the month?")
var monthDays = 0

for( i = 1 ; i < todaysMonth ; i++) {
monthDays += daysofMonth()[i - 1]
}

var totalDays = +monthDays + +todaysDay
var daysLeft = 365 - +totalDays

console.log("Today is day number " + totalDays + "/365 of 2015. Only " + daysLeft + " left until the end of the year!")


#2

I'd restructure the function what about giving it parameters? One parameter for the month and one for leap year. Also you can store the array in a variable and if leap year is true and month > 2 you just add 1 to the sum of days :smile:

Also what about taking a date as input and deducing the leap year question yourself e.g. is divisible by 4 but not by 100 but again by 400?