Functional Weave
Code in Rust

dates.week-number@1.0.0

impl/typescript.ts

768 bytes · the TypeScript implementation · view raw

Imports name this capability’s declared dependencies, which fune builds next to it in your project; each one links to its page.

import { civilFromDays, daysFromCivil, epochDayFromIso } from "./dates_add_days.ts";  ← from dates.add-days ^1.0.0 · built alongside by fune
import { dayOfWeek } from "./dates_day_of_week.ts";  ← from dates.day-of-week ^1.0.0 · built alongside by fune
import { type IsoWeek } from "./dates_week_number_types.ts";

/**
 * The ISO 8601 week of a date. The Thursday of the date's Monday-to-Sunday
 * week decides everything: its calendar year is the week-year, and its day of
 * that year gives the week number.
 */
export function weekNumber(iso: string): IsoWeek {
  const thursday = epochDayFromIso(iso) + (4 - dayOfWeek(iso));
  const weekYear = civilFromDays(thursday).year;
  const week = Math.floor((thursday - daysFromCivil(weekYear, 1, 1)) / 7) + 1;
  return {
    weekYear,
    week,
    label: `${String(weekYear).padStart(4, "0")}-W${String(week).padStart(2, "0")}`,
  };
}