← #109 Combine Google font requests
#110

Use Array.includes for multiple conditionals

Topics: JavaScript

Let's consider a function that determines the total number of days in a given month.

const getDays = (month, year) => {
...
};

Since months in JavaScripts start from 0, we assume that the month parameter is zero-based index. We can make the function quickly return if the month is April, June, September or November:

if (month === 3 || month === 5 || month === 8 || month === 10) {
return 30;
}
...

These conditionals can be replaced with a single check by using the Array.includes function:

if ([3, 5, 8, 10].includes(month)) {
return 30;
}
...

For this specific function, we can use a lookup table:

const isLeapYear = year => (
(year % 4) === 0 && ((year % 100) !== 0 || (year % 400) === 0)
);

const getDays = (month, year) => (
[
31,
(isLeapYear(year) ? 29 : 28),
31, 30, 31, 30, 31, 31, 30, 31, 30, 31
][month]
);

More

Fix a typo or suggest an improvement
#111 Ignore case sensitivity in a CSS attribute selector