All files iso-week-of-year.ts

100% Statements 32/32
100% Branches 6/6
100% Functions 1/1
100% Lines 32/32

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 671x 1x 1x 1x                                                   1x 96x 96x 96x 96x 96x 96x           96x 96x   96x 96x 24x 24x 24x 24x 72x 72x 72x 72x   96x 96x 96x   96x 1x 1x 1x   96x 96x  
import { beginningOfWeek } from './beginning-of-week.ts';
import { day, type DayOfWeek, month, ticksPerWeek } from './date.ts';
import { floor } from './floor.ts';
import { isoWeeksInYear } from './iso-weeks-in-year.ts';
 
/**
 * Options for the {@link isoWeekOfYear} function
 * @group Time
 * @category Week
 */
export type ISOWeekOfYearOptions = {
  /** Use the utc timezone */
  utc?: boolean;
  /** Week 1 is defined as the week with the Gregorian year's first [weekOneIncludes] day in it */
  weekOneIncludes?: DayOfWeek;
  /** The first day of the week */
  firstDayOfWeek?: DayOfWeek;
};
 
/**
 * Determine the ISO week number for a given date
 * @param input - The date
 * @param options - see {@link ISOWeekOfYearOptions}
 * @defaultValue weekOneIncludes Thursday
 * @defaultValue firstDayOfWeek Monday
 * @returns the week number (1-53)
 * @group Time
 * @category Week
 */
export function isoWeekOfYear(
  input: Date,
  {
    utc = false,
    weekOneIncludes = day.thursday,
    firstDayOfWeek = day.monday,
  }: ISOWeekOfYearOptions = {},
): {
  /** The year */
  year: number;
  /** The ISO week number */
  week: number;
} {
  const bow = beginningOfWeek(input, { utc, firstDayOfWeek });
 
  const week1 =
    utc ?
      beginningOfWeek(new Date(Date.UTC(bow.getUTCFullYear(), month.january, weekOneIncludes)), {
        utc,
        firstDayOfWeek,
      })
    : beginningOfWeek(new Date(bow.getFullYear(), month.january, weekOneIncludes), {
        utc,
        firstDayOfWeek,
      });
 
  let week = 1 + floor((bow.getTime() - week1.getTime()) / ticksPerWeek, { tolerance: 0.05 });
  let year = utc ? bow.getUTCFullYear() : bow.getFullYear();
  const weeks = isoWeeksInYear(year, { utc, weekOneIncludes });
 
  if (week > weeks) {
    year += 1;
    week = 1;
  }
 
  return { year, week };
}