user2444354
user2444354

Reputation: 11

Is there a more efficient way to do this without all the "if" and "else" statements?

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

Answers (4)

Diode
Diode

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

Niet the Dark Absol
Niet the Dark Absol

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

maethorr
maethorr

Reputation: 594

If you are ok with including a third party library, try this library:

http://momentjs.com/

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

jcsanyi
jcsanyi

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

Related Questions