0

I have the following code and I want to know if there is a better way to simplify it.
I need to use simple data structures (yes, for each, etc.)

function amountDayMonth(month) {
    let amountDayMonth
    if(month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12) {
        amountDayMonth = 31;
    } else if (month == 4 || month == 6 || month == 9 || month == 11) {
        amountDayMonth = 30;
    } else if(month == 2) {
        amountDayMonth = 28;
    }
    return amountDayMonth;
}


Thanks!

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Cristian
  • 111
  • 7

4 Answers4

2

The simplest solution by far is to ABUSE the Date object

function amountDayMonth(month) {
    return new Date(2019, month, 0).getDate();
}

month is 0 based, so using month, you're creating a date of the 0th day in the next month, which is the last day of month .. which is the length of the month

Then you need to fix february if it's a leap year

or

function amountDayMonth(year, month) {
  return new Date(year, month, 0).getDate();
}
console.log(amountDayMonth(2019, 4)); // 30
console.log(amountDayMonth(2019, 2)); // 28
console.log(amountDayMonth(2020, 2)); // 29
console.log(amountDayMonth(2019,12)); // 31

Done

no if's or switch's required

Jaromanda X
  • 53,868
  • 5
  • 73
  • 87
1

Another suggestion to rewrite your logic in one line:

  1. use Number.isInteger(month) && month >= 1 && month <= 12 to check for undefined
  2. use month % 2 == +(month <= 7) to check for 31
  3. use month == 2 to check for 28
  4. the rest is 30

function amountDayMonth(month)
{
  return (Number.isInteger(month) && month >= 1 && month <= 12) ? (month % 2 == +(month <= 7) ? 31 : (month == 2 ? 28 : 30)) : undefined
}
[0,1,2,3,4,5,6,7,8,9,10,11,12,13].forEach(x=>console.log(amountDayMonth(x)))
Ricky Mo
  • 6,285
  • 1
  • 14
  • 30
0

You could preset and array and check against it for expected values like so:

const expectedMonths = [1,3,5,7,8,10,12];

if (expectedMonths.indexof(month)>-1) {
    amountDayMonth = 31;
}

Or since your data is pretty much static, just have an existing table of values

let amountDayMonth = month => [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][month]
jkris
  • 5,851
  • 1
  • 22
  • 30
0

You can use an array lookup. Showing Java example, since you indicated you want either.

private static final int[] DAYS = {31,28,31,30,31,30,31,31,30,31,30,31};
public int amountDayMonth(int month) {
    return DAYS[month - 1];
}

If you don't like array like that, you can use ternary operator:

public int amountDayMonth(int month) {
    return (month == 2 ? 28 : month == 4 || month == 6 || month == 9 || month == 11 ? 30 : month >= 1 && month <= 12 ? 31 : 0);
}
Andreas
  • 154,647
  • 11
  • 152
  • 247