Reputation: 11
How would you program this more efficiently?
if( randomYear%4==0 ) {
if( randomYear%100==0 ) {
if( randomYear%400==0 ) {
randomDay = 1 + Math.floor(Math.random()*29);
}
else {
randomDay = 1 + Math.floor(Math.random()*28);
}
else{
randomDay = 1 + Math.floor(Math.random()*29);
}
else{
randomDay = 1 + Math.floor(Math.random()*28);
}
First off, i''m using math.floor because it includes 0 and excludes 1, which is what i'm looking for. The purpose of this is to determine if the variable 'randomYear' is a leap year and have the appropriate days in February.
I'm mainly concerned about all the if and else statements. BTW, i'm using Javascript. Thank YOU SO much!!
Upvotes: 1
Views: 119
Reputation: 25135
You can do it as given below.
function isLeapYear(year){
return !(year%400) || ((year%100 > 0) && !(year%4)) ;
}
function getRandomDay(year){
return 1 + Math.floor(Math.random()* (isLeapYear(year)?29:28))
}
var day = getRandomDay(2000);
Performance wise it might not make big changes. But this is the way to write organized re-usable code in less number of lines.
Upvotes: 0
Reputation: 324620
You don't even need the math:
var tmp = new Date(year,1,29); // attempt to get February 29th
isleapyear = (tmp.getMonth() == 1);
Upvotes: 5
Reputation: 594
If you are ok with including a third party library, try this library:
And you can just do:
moment([2000]).isLeapYear()
to check if 2000 is a leap year and then you can do appropriate logic. Also you can check if 29th of Feb of a certain year exists or not using its validation api.
Upvotes: 1
Reputation: 8174
How about this?
var maxDays = 28;
if (randomYear%4 == 0 && (randomYear%100 != 0 || randomYear%400 == 0)) {
maxDays = 29;
}
randomDay = 1 + Math.floor(Math.random() * maxDays);
Upvotes: 1