Skip to content

Commit

Permalink
fix: Sundays can begin weekday ranges (#320)
Browse files Browse the repository at this point in the history
  • Loading branch information
tehpsalmist authored Jul 29, 2024
1 parent ecb151a commit 1cce462
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 1 deletion.
12 changes: 11 additions & 1 deletion src/cron-parser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -128,7 +128,7 @@ function parseElement(element: string, constraint: IConstraint): Set<number> {
}

// If it is a range, get start and end of the range.
const parsedStart =
let parsedStart =
rangeSegments[1] === '*'
? constraint.min
: parseSingleElement(rangeSegments[2])
Expand All @@ -138,6 +138,16 @@ function parseElement(element: string, constraint: IConstraint): Set<number> {
? constraint.max
: parseSingleElement(rangeSegments[3])

// need to catch Sunday, which gets parsed here as 7, but is also legitimate at the start of a range as 0, to avoid the out of order error
if (
constraint === weekdayConstraint &&
parsedStart === 7 &&
// this check ensures that sun-sun is not incorrectly parsed as [0,1,2,3,4,5,6]
parsedEnd !== 7
) {
parsedStart = 0
}

if (parsedStart > parsedEnd) {
throw new Error(
`Failed to parse ${element}: Invalid range (start: ${parsedStart}, end: ${parsedEnd}).`,
Expand Down
18 changes: 18 additions & 0 deletions test/cron-parser.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -310,6 +310,24 @@ describe('parseCronExpression', () => {
months: [0],
weekdays: [4, 5, 6],
})

expect(parseCronExpression('0 0 0 1 1 Sun-wed,Fri')).toMatchObject({
seconds: [0],
minutes: [0],
hours: [0],
days: [1],
months: [0],
weekdays: [0, 1, 2, 3, 5],
})

expect(parseCronExpression('0 0 0 1 1 sun-sun')).toMatchObject({
seconds: [0],
minutes: [0],
hours: [0],
days: [1],
months: [0],
weekdays: [0],
})
})

test('Should default to 0 when no seconds are specified in the cron expression', () => {
Expand Down

0 comments on commit 1cce462

Please sign in to comment.