mirror of
https://github.com/TheAlgorithms/JavaScript.git
synced 2026-03-13 15:21:15 +08:00
refactor: add and use parseDate (#1643)
* refactor: add and use `parseDate` * style: use proper spelling Co-authored-by: appgurueu <34514239+appgurueu@users.noreply.github.com> --------- Co-authored-by: appgurueu <34514239+appgurueu@users.noreply.github.com>
This commit is contained in:
27
Timing-Functions/ParseDate.js
Normal file
27
Timing-Functions/ParseDate.js
Normal file
@@ -0,0 +1,27 @@
|
||||
import { getMonthDays } from './GetMonthDays'
|
||||
|
||||
function checkDate(date) {
|
||||
if (date.day < 1 || date.day > getMonthDays(date.month, date.year)) {
|
||||
throw new Error('Invalid day value.')
|
||||
}
|
||||
}
|
||||
|
||||
function parseDate(dateString) {
|
||||
const regex = /^(\d{1,2})\/(\d{1,2})\/(\d{4})$/
|
||||
|
||||
const match = dateString.match(regex)
|
||||
|
||||
if (!match) {
|
||||
throw new Error("Invalid date format. Please use 'dd/mm/yyyy'.")
|
||||
}
|
||||
|
||||
const res = {
|
||||
day: parseInt(match[1], 10),
|
||||
month: parseInt(match[2], 10),
|
||||
year: parseInt(match[3], 10)
|
||||
}
|
||||
checkDate(res)
|
||||
return res
|
||||
}
|
||||
|
||||
export { parseDate }
|
||||
40
Timing-Functions/test/ParseDate.test.js
Normal file
40
Timing-Functions/test/ParseDate.test.js
Normal file
@@ -0,0 +1,40 @@
|
||||
import { parseDate } from '../ParseDate'
|
||||
|
||||
describe('parseDate', () => {
|
||||
it.each([
|
||||
['18/03/2024', { year: 2024, month: 3, day: 18 }],
|
||||
['29/02/2024', { year: 2024, month: 2, day: 29 }],
|
||||
['28/02/2023', { year: 2023, month: 2, day: 28 }],
|
||||
['01/12/2024', { year: 2024, month: 12, day: 1 }],
|
||||
['1/12/2024', { year: 2024, month: 12, day: 1 }],
|
||||
['10/1/2024', { year: 2024, month: 1, day: 10 }]
|
||||
])('Returns correct output for %s', (dateString, expected) => {
|
||||
expect(parseDate(dateString)).toStrictEqual(expected)
|
||||
})
|
||||
|
||||
it.each([
|
||||
'18-03-2024',
|
||||
'18.03.2024',
|
||||
'03/2024',
|
||||
'01/02/03/2024',
|
||||
'123/03/2024'
|
||||
])('Throws for %s', (wrongDateString) => {
|
||||
expect(() => {
|
||||
parseDate(wrongDateString)
|
||||
}).toThrow()
|
||||
})
|
||||
|
||||
it.each([
|
||||
'40/03/2024',
|
||||
'30/02/2024',
|
||||
'29/02/2023',
|
||||
'31/04/2023',
|
||||
'00/01/2024',
|
||||
'01/00/2024',
|
||||
'01/13/2024'
|
||||
])('Throws for %s', (wrongDateString) => {
|
||||
expect(() => {
|
||||
parseDate(wrongDateString)
|
||||
}).toThrow()
|
||||
})
|
||||
})
|
||||
Reference in New Issue
Block a user