Created
May 20, 2016 08:37
-
-
Save webpapaya/bcd9de9a8b825e8d8b51f862b0f570dd to your computer and use it in GitHub Desktop.
How would you improve this code?
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { | |
assertThat, | |
equalTo, | |
} from 'hamjest'; | |
import { getDaysInMonth } from './day'; | |
describe('getDaysInMonth()', () => { | |
it('April has 30 days', () => | |
assertThat(getDaysInMonth(4, 2016), equalTo(30))); | |
it('June has 30 days', () => | |
assertThat(getDaysInMonth(6, 2016), equalTo(30))); | |
it('Sept has 30 days', () => | |
assertThat(getDaysInMonth(9, 2016), equalTo(30))); | |
it('Nov has 30 days', () => | |
assertThat(getDaysInMonth(11, 2016), equalTo(30))); | |
describe('leap years', () => { | |
it('Feb in 1900 has 28 days', () => | |
assertThat(getDaysInMonth(2, 1900), equalTo(28))); | |
it('Feb in 1994 has 28 days', () => | |
assertThat(getDaysInMonth(2, 1994), equalTo(28))); | |
it('Feb in 1996 has 29 days', () => | |
assertThat(getDaysInMonth(2, 1996), equalTo(29))); | |
it('Feb in 1997 has 28 days', () => | |
assertThat(getDaysInMonth(2, 1997), equalTo(28))); | |
it('Feb in 2000 has 29 days', () => | |
assertThat(getDaysInMonth(2, 2000), equalTo(29))); | |
it('Feb in 2016 has 29 days', () => | |
assertThat(getDaysInMonth(2, 2016), equalTo(29))); | |
it('Feb in 2400 has 29 days', () => | |
assertThat(getDaysInMonth(2, 2400), equalTo(29))); | |
it('Feb in 2401 has 28 days', () => | |
assertThat(getDaysInMonth(2, 2401), equalTo(28))); | |
}); | |
}); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export const getDaysInMonth = (month, year) => { | |
const isFebruary = month === 2; | |
const isLeapYear = (!(year % 4) && year % 100) || !(year % 400); | |
if(isFebruary) { | |
return isLeapYear ? 29 : 28; | |
} | |
const SEPTEMBER = 9; | |
const APRIL = 4; | |
const JUNE = 6; | |
const NOVEMBER = 11; | |
const is30DaysMonth = new RegExp(`${SEPTEMBER}|${APRIL}|${JUNE}|${NOVEMBER}`).test(month); | |
return is30DaysMonth ? 30 : 31; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment