Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add next weekday function #104

Merged
merged 1 commit into from
Oct 3, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions Date.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -123,6 +123,16 @@ describe("Date", () => {
expect(isoly.Date.getWeekDay("2022-05-07")).toEqual(6) // Saturday
expect(isoly.Date.getWeekDay("2022-05-08")).toEqual(0) // Sunday
})
it("nextWeekday", () => {
expect(isoly.Date.nextWeekday("2022-05-04")).toEqual("2022-05-05") // Wednesday -> Thursday
expect(isoly.Date.nextWeekday("2022-05-04", 2)).toEqual("2022-05-06") // Wednesday -> Friday
expect(isoly.Date.nextWeekday("2022-05-04", 3)).toEqual("2022-05-09") // Wednesday -> Monday
expect(isoly.Date.nextWeekday("2022-05-04", 4)).toEqual("2022-05-09") // Wednesday -> Monday
expect(isoly.Date.nextWeekday("2022-05-04", 5)).toEqual("2022-05-09") // Wednesday -> Monday
expect(isoly.Date.nextWeekday("2022-05-04", 6)).toEqual("2022-05-10") // Wednesday -> Tuesday
expect(isoly.Date.nextWeekday("2023-11-30", 1, ["2023-12-01"])).toEqual("2023-12-04") // Thursday -> Monday
expect(isoly.Date.nextWeekday("2023-11-30", 1, ["2023-12-01", "2023-12-04"])).toEqual("2023-12-05") // Thursday -> Tuesday
})
it("invalid date", () => {
expect(isoly.Date.is("2020-13-31")).toEqual(false)
})
Expand Down
10 changes: 10 additions & 0 deletions Date.ts
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,16 @@ export namespace Date {
export function getWeekDay(time: Date): number {
return new globalThis.Date(time).getDay()
}
export function nextWeekday(date: Date, days: number | DateSpan = 1, holidays: Date[] = []): Date {
const holidaySet = new Set(holidays)
let result = next(date, days)
let weekday = getWeekDay(result)
while (weekday == 6 || weekday == 0 || holidaySet.has(result)) {
result = next(result, weekday == 6 ? 2 : 1)
weekday = getWeekDay(result)
}
return result
}
export function span(date: Date, relative: Date): DateSpan {
return {
years: getYear(date) - getYear(relative),
Expand Down