mirror of
https://github.com/TheAlgorithms/JavaScript.git
synced 2025-07-05 00:01:37 +08:00
Add Get Numbers of Days of a Month (#464)
This commit is contained in:
33
Timing-Functions/GetMonthDays.js
Normal file
33
Timing-Functions/GetMonthDays.js
Normal file
@ -0,0 +1,33 @@
|
||||
/**
|
||||
function that takes month number and its year and returns the number of days within it
|
||||
* @param monthNumber.
|
||||
* @param year.
|
||||
e.g.: mahfoudh.arous@gmail.com -> true
|
||||
e.g.: mahfoudh.arous.com ->false
|
||||
*/
|
||||
|
||||
const getMonthDays = (monthNumber, year) => {
|
||||
const the31DaysMonths = [1, 3, 5, 7, 8, 10, 12]
|
||||
const the30DaysMonths = [4, 6, 9, 11]
|
||||
|
||||
if (!the31DaysMonths.includes(monthNumber) && !the30DaysMonths.includes(monthNumber) &&
|
||||
(monthNumber !== 2)
|
||||
) {
|
||||
throw new TypeError('Invalid Month Number.')
|
||||
}
|
||||
|
||||
if (the31DaysMonths.includes(monthNumber)) { return 31 }
|
||||
|
||||
if (the30DaysMonths.includes(monthNumber)) { return 30 }
|
||||
|
||||
// Check for Leap year
|
||||
if (year % 4 === 0) {
|
||||
if ((year % 100 !== 0) || (year % 100 === 0 && year % 400 === 0)) {
|
||||
return 29
|
||||
}
|
||||
}
|
||||
|
||||
return 28
|
||||
}
|
||||
|
||||
export { getMonthDays }
|
19
Timing-Functions/GetMonthDays.test.js
Normal file
19
Timing-Functions/GetMonthDays.test.js
Normal file
@ -0,0 +1,19 @@
|
||||
import { getMonthDays } from './GetMonthDays'
|
||||
|
||||
describe('Get the Days of a Month', () => {
|
||||
it('expects to return 28', () => {
|
||||
expect(getMonthDays(2, 2018)).toEqual(28)
|
||||
})
|
||||
|
||||
it('expects to return 30', () => {
|
||||
expect(getMonthDays(6, 254)).toEqual(30)
|
||||
})
|
||||
|
||||
it('expects to return 29', () => {
|
||||
expect(getMonthDays(2, 2024)).toEqual(29)
|
||||
})
|
||||
|
||||
it('expects to throw a type error', () => {
|
||||
expect(() => { getMonthDays(13, 2020) }).toThrow('Invalid Month Number.')
|
||||
})
|
||||
})
|
Reference in New Issue
Block a user