Skip to content

Commit

Permalink
Optimized broadcast week calculation
Browse files Browse the repository at this point in the history
  • Loading branch information
velocityzen committed Mar 8, 2024
1 parent 793875e commit 415c8a6
Showing 1 changed file with 1 addition and 26 deletions.
27 changes: 1 addition & 26 deletions src/week.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,17 +2,6 @@ import { DateTime } from "luxon";

import { IfValid, isValid } from "./helpers";

const DAY = 24 * 60 * 60 * 1000;

function isLastWeekOverflown(date: DateTime): boolean {
const yearEnd = date.endOf("year");
const yearEndWeekDay = yearEnd.weekday;
if (yearEndWeekDay === 7) {
return false;
}
return yearEnd.toMillis() - date.toMillis() <= yearEndWeekDay * DAY;
}

/**
* returns broadcast week number (1-54) for a given date
**/
Expand All @@ -23,19 +12,5 @@ export function getBroadcastWeek<IsValid extends boolean>(
return null as IfValid<IsValid, number>;
}

const day = date.startOf("day");

if (isLastWeekOverflown(day)) {
return 1 as IfValid<IsValid, number>;
}

const yearStart = day.startOf("year");
const yearStartWeekDay = yearStart.weekday - 1;
const weekNo = Math.ceil(
((day.valueOf() - yearStart.toMillis() + yearStartWeekDay * DAY) / DAY +
1) /
7,
);

return weekNo as IfValid<IsValid, number>;
return Math.ceil(date.endOf("week").ordinal / 7) as IfValid<IsValid, number>;
}

0 comments on commit 415c8a6

Please sign in to comment.