Skip to content

Commit

Permalink
feat: day of the week literals
Browse files Browse the repository at this point in the history
  • Loading branch information
kbariotis committed Jan 5, 2022
1 parent f6dc6c6 commit 3512702
Show file tree
Hide file tree
Showing 3 changed files with 66 additions and 5 deletions.
4 changes: 4 additions & 0 deletions src/lib/on.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,4 +8,8 @@ describe('on', () => {
it('should provide on 3rd day of the month', () => {
expect(onDayOfTheMonth(3).toString()).toBe('0 0 3 * *');
});

it('should provide day of the week using literals', () => {
expect(onDayOfTheWeek('Sunday').toString()).toBe('0 0 * * 0');
});
});
56 changes: 52 additions & 4 deletions src/lib/on.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,14 @@
import { DayOfTheMonthExpression, DayOfTheWeekExpression } from './expression';

/**
* In specific day of the month
*
* ```
* onDayOfTheMonth(3); // * * 3 * *
* onDayOfTheMonth([3,5]); // * * 3,5 * *
* ```
*
*/
export const onDayOfTheMonth = (
dayOfTheMonth: DayOfTheMonth | DayOfTheMonth[]
) => {
Expand All @@ -12,12 +21,51 @@ export const onDayOfTheMonth = (
});
};

export const onDayOfTheWeek = (dayOfTheWeek: DayOfTheWeek | DayOfTheWeek[]) => {
const map = {
Monday: 1,
Tuesday: 2,
Wednesday: 3,
Thursday: 4,
Friday: 5,
Saturday: 6,
Sunday: 0,
};

/**
* In specific day of the week
*
* ```
* onDayOfTheWeek(3); // 0 0 * * 3
* onDayOfTheWeek([3,5]); // 0 0 * * 3,5
*
* onDayOfTheWeek('Monday'); // 0 0 * * 1
* onDayOfTheWeek(['Sunday', 'Thursday']); // 0 0 * * 0,4
* ```
*/
export const onDayOfTheWeek = (
dayOfTheWeek:
| DayOfTheWeek
| DayOfTheWeek[]
| DayOfTheWeekLiteral
| DayOfTheWeekLiteral[]
) => {
const arrayInput = Array.isArray(dayOfTheWeek)
? dayOfTheWeek
: [dayOfTheWeek];

if (typeof arrayInput[0] === 'string') {
return new DayOfTheWeekExpression({
minute: '0',
hour: '0',
dayOfTheWeek: (arrayInput as DayOfTheWeekLiteral[])
.map((day) => map[day])
.join(','),
});
}

return new DayOfTheWeekExpression({
minute: '0',
hour: '0',
dayOfTheWeek: `${
Array.isArray(dayOfTheWeek) ? dayOfTheWeek.join(',') : dayOfTheWeek
}`,
dayOfTheWeek: arrayInput.join(','),
});
};
11 changes: 10 additions & 1 deletion src/lib/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -140,4 +140,13 @@ type DayOfTheMonth =
| 31;

// eslint-disable-next-line @typescript-eslint/no-unused-vars
type DayOfTheWeek = 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7;
type DayOfTheWeek = 0 | 1 | 2 | 3 | 4 | 5 | 6;
// eslint-disable-next-line @typescript-eslint/no-unused-vars
type DayOfTheWeekLiteral =
| 'Monday'
| 'Tuesday'
| 'Wednesday'
| 'Thursday'
| 'Friday'
| 'Saturday'
| 'Sunday';

0 comments on commit 3512702

Please sign in to comment.