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 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 | 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 4x 4x 4x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 30x 30x 30x 1x 1x 29x 30x 1x 1x 1x 1x 1x 1x 1x 1x 13x 13x 13x 13x 13x 13x 13x 13x 1x 1x 1x 1x 1x 1x 10x 10x 1x 1x 1x 1x 1x 9x 9x 9x 9x 9x 9x 2x 2x 7x 9x 1x 1x 1x 1x 5x 5x 1x 1x 7x 7x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 4x 4x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 2x 2x 2x 24x 24x 2x 2x 1x 1x 1x 1x 1x 1x 2x 2x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 8x 8x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 2x 2x 1x 1x 1x 1x 5x 5x 5x 5x 5x 5x 5x 5x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 1x 1x 1x 1x 1x 1x 1x 1x 1x 4x 4x 4x 4x 4x 4x 4x 1x 1x 1x 1x 1x 3x 4x 1x 1x 1x 1x 1x 1x 2x 2x 4x 1x 1x 1x 1x 4x 1x 1x 1x | import { Temporal } from '@js-temporal/polyfill';
import type { CalendarEngine } from 'hijri-core';
type DateUnit = 'year' | 'years' | 'month' | 'months' | 'week' | 'weeks' | 'day' | 'days';
/** Reference year for monthDay construction when no year is specified. */
const REFERENCE_YEAR = 1444;
/**
* Borrow days/months so that a Hijri date difference has non-negative components.
*
* Shared by the 'years' and 'months' branches of dateUntil() to avoid
* duplicating the borrow logic.
*/
function borrowHijriDiff(
engine: CalendarEngine,
years: number,
months: number,
days: number,
h2: { hy: number; hm: number },
): { years: number; months: number; days: number } {
// Borrow from months when days are negative.
if (days < 0) {
months--;
let borrowHm = h2.hm - 1;
let borrowHy = h2.hy;
if (borrowHm < 1) {
borrowHm = 12;
borrowHy--;
}
days += engine.daysInMonth(borrowHy, borrowHm);
}
// Borrow from years when months are negative.
if (months < 0) {
years--;
months += 12;
}
return { years, months, days };
}
/**
* Base class implementing the TC39 Temporal Calendar Protocol for Hijri calendars.
*
* Coordinate bridging: Temporal.PlainDate operates in the ISO (Gregorian) calendar.
* Every calendar method receives a PlainDate with ISO year/month/day, and must
* return results in the Hijri calendar's coordinate system. The bridge is
* toHijri() and fromHijri(), which delegate to the injected CalendarEngine.
*
* Arithmetic strategy for dateAdd():
* - Year and month deltas are applied in Hijri space (correct handling of
* variable month lengths).
* - Day and week deltas are applied in ISO space after the Hijri addition,
* so that "add 30 days" always means exactly 30 days.
*/
export class HijriCalendar {
protected readonly engine: CalendarEngine;
readonly id: string;
constructor(engine: CalendarEngine) {
this.engine = engine;
this.id = `hijri-${engine.id}`;
}
toString(): string {
return this.id;
}
/**
* Convert a Temporal.PlainDate (ISO calendar) to Hijri coordinates.
*
* Uses the local-time Date constructor so that the date components passed to
* the engine match the calendar date exactly, regardless of host timezone.
* The UAQ engine reads local components; the FCNA engine reads UTC components.
* Because we construct with new Date(y, m, d) the local date always matches
* the intended calendar date.
*/
protected toHijri(date: Temporal.PlainDate): { hy: number; hm: number; hd: number } {
const jsDate = new Date(date.year, date.month - 1, date.day);
const hijri = this.engine.toHijri(jsDate);
if (!hijri) {
throw new RangeError(`Date ${date.toString()} is out of range for the ${this.id} calendar`);
}
return hijri;
}
/**
* Convert Hijri coordinates to a Temporal.PlainDate (ISO calendar).
*
* The engine returns a Date whose UTC components represent the Gregorian date.
* We extract those UTC components to construct the PlainDate.
*/
protected fromHijri(hy: number, hm: number, hd: number): Temporal.PlainDate {
const greg = this.engine.toGregorian(hy, hm, hd);
if (!greg) {
throw new RangeError(
`Hijri date ${hy}/${hm}/${hd} is out of range for the ${this.id} calendar`,
);
}
return Temporal.PlainDate.from({
year: greg.getUTCFullYear(),
month: greg.getUTCMonth() + 1,
day: greg.getUTCDate(),
});
}
/**
* Resolve the overflow option from a Temporal options bag.
* Returns 'constrain' (the default) or 'reject'.
*/
private resolveOverflow(options?: { overflow?: 'constrain' | 'reject' }): 'constrain' | 'reject' {
return options?.overflow ?? 'constrain';
}
/**
* Clamp or reject a day value based on the overflow setting.
*/
private applyOverflow(
day: number,
maxDay: number,
month: number,
overflow: 'constrain' | 'reject',
): number {
if (overflow === 'reject' && day > maxDay) {
throw new RangeError(`Day ${day} exceeds ${maxDay} days in month ${month}`);
}
return Math.min(day, maxDay);
}
// ── Field accessors ───────────────────────────────────────────────────────
year(date: Temporal.PlainDate): number {
return this.toHijri(date).hy;
}
month(date: Temporal.PlainDate): number {
return this.toHijri(date).hm;
}
/**
* Month code per the Temporal proposal: "M01".."M12".
* Hijri months are always 1-12 (no leap/intercalary month), so the code is
* simply the zero-padded month number.
*/
monthCode(date: Temporal.PlainDate): string {
const { hm } = this.toHijri(date);
return `M${String(hm).padStart(2, '0')}`;
}
day(date: Temporal.PlainDate): number {
return this.toHijri(date).hd;
}
// ── Month and year metrics ─────────────────────────────────────────────────
daysInMonth(date: Temporal.PlainDate): number {
const { hy, hm } = this.toHijri(date);
return this.engine.daysInMonth(hy, hm);
}
/**
* Sum all 12 month lengths for the Hijri year. Standard lunar years are 354
* days; leap years (with an added day in Dhul-Hijja) are 355 days.
*/
daysInYear(date: Temporal.PlainDate): number {
const { hy } = this.toHijri(date);
let total = 0;
for (let m = 1; m <= 12; m++) {
total += this.engine.daysInMonth(hy, m);
}
return total;
}
monthsInYear(_date: Temporal.PlainDate): number {
return 12;
}
inLeapYear(date: Temporal.PlainDate): boolean {
return this.daysInYear(date) === 355;
}
// ── Day-of-week and day-of-year ────────────────────────────────────────────
/**
* ISO weekday: 1 = Monday, 7 = Sunday.
* PlainDate.dayOfWeek on an ISO-calendar date already gives ISO weekday,
* so no conversion is needed.
*/
dayOfWeek(date: Temporal.PlainDate): number {
return date.dayOfWeek;
}
/**
* Day within the Hijri year. Accumulates full months before the current one,
* then adds the day-of-month offset.
*/
dayOfYear(date: Temporal.PlainDate): number {
const { hy, hm, hd } = this.toHijri(date);
let total = hd;
for (let m = 1; m < hm; m++) {
total += this.engine.daysInMonth(hy, m);
}
return total;
}
/** Hijri week number counted from day 1 of Muharram (day 1-7 = week 1). No ISO week alignment. */
weekOfYear(date: Temporal.PlainDate): number {
return Math.ceil(this.dayOfYear(date) / 7);
}
daysInWeek(_date: Temporal.PlainDate): number {
return 7;
}
// ── Temporal Calendar Protocol: fields() ──────────────────────────────────
/**
* Return the list of fields that the calendar adds to a Temporal object.
* Non-era calendars return the input array unchanged.
*/
fields(fields: string[]): string[] {
return fields;
}
// ── Construction from fields ───────────────────────────────────────────────
dateFromFields(
fields: { year: number; month: number; day: number },
options?: { overflow?: 'constrain' | 'reject' },
): Temporal.PlainDate {
const overflow = this.resolveOverflow(options);
const maxDay = this.engine.daysInMonth(fields.year, fields.month);
const day = this.applyOverflow(fields.day, maxDay, fields.month, overflow);
return this.fromHijri(fields.year, fields.month, day);
}
/**
* ISO-anchored PlainYearMonth per the Temporal Calendar Protocol.
* The resulting PlainYearMonth stores ISO coordinates internally, representing
* the Hijri month that starts on that ISO year/month.
*/
yearMonthFromFields(
fields: { year: number; month: number },
options?: { overflow?: 'constrain' | 'reject' },
): Temporal.PlainYearMonth {
const overflow = this.resolveOverflow(options);
// Clamp month to 1-12 or reject.
const maxMonth = 12;
if (overflow === 'reject' && (fields.month < 1 || fields.month > maxMonth)) {
throw new RangeError(`Month ${fields.month} is out of range 1-${maxMonth}`);
}
const month = Math.max(1, Math.min(fields.month, maxMonth));
const isoDate = this.fromHijri(fields.year, month, 1);
return Temporal.PlainYearMonth.from({
year: isoDate.year,
month: isoDate.month,
});
}
/**
* ISO-anchored PlainMonthDay per the Temporal Calendar Protocol.
* Reference year 1444 is intentional: it is a recent, well-covered UAQ year
* used to anchor the ISO coordinates when no year is supplied.
*/
monthDayFromFields(
fields: { month: number; day: number; year?: number },
options?: { overflow?: 'constrain' | 'reject' },
): Temporal.PlainMonthDay {
const overflow = this.resolveOverflow(options);
const year = fields.year ?? REFERENCE_YEAR;
const maxDay = this.engine.daysInMonth(year, fields.month);
const day = this.applyOverflow(fields.day, maxDay, fields.month, overflow);
const isoDate = this.fromHijri(year, fields.month, day);
return Temporal.PlainMonthDay.from({
month: isoDate.month,
day: isoDate.day,
});
}
// ── Arithmetic ─────────────────────────────────────────────────────────────
/**
* Add a duration to a Hijri date.
*
* Year and month additions are handled in Hijri space to preserve calendar
* semantics (e.g., adding one month to 1 Ramadan yields 1 Shawwal, not a
* fixed 30-day offset). Day and week additions are then applied in ISO space
* so that they always represent exact day counts.
*
* Month normalization uses O(1) modular arithmetic instead of iterative loops.
* When the day-of-month exceeds the target month's length after a Hijri-space
* adjustment, it is clamped to the last valid day of that month.
*/
dateAdd(
date: Temporal.PlainDate,
duration: Temporal.Duration,
_options?: { overflow?: 'constrain' | 'reject' },
): Temporal.PlainDate {
const { hy, hm, hd } = this.toHijri(date);
const years = duration.years ?? 0;
const months = duration.months ?? 0;
// O(1) month normalization via modular arithmetic.
const totalMonths = (hy - 1) * 12 + (hm - 1) + years * 12 + months;
let newHy = Math.floor(totalMonths / 12) + 1;
let newHm = (totalMonths % 12) + 1;
// Handle negative modulo (JS % can return negative values).
if (newHm < 1) {
newHm += 12;
newHy--;
}
// Clamp day to the valid range for the target month.
const maxDay = this.engine.daysInMonth(newHy, newHm);
const clampedDay = Math.min(hd, maxDay);
// Convert the Hijri result back to ISO, then apply the day/week delta.
const intermediate = this.fromHijri(newHy, newHm, clampedDay);
const dayDelta = (duration.days ?? 0) + (duration.weeks ?? 0) * 7;
return dayDelta !== 0 ? intermediate.add({ days: dayDelta }) : intermediate;
}
/**
* Compute the difference between two Hijri dates.
*
* For simplicity and correctness across variable-length Hijri months, this
* delegates to the underlying ISO PlainDate difference when the largest unit
* is days or weeks. Year/month differences require a Hijri-space calculation.
*/
dateUntil(
one: Temporal.PlainDate,
two: Temporal.PlainDate,
options?: { largestUnit?: DateUnit },
): Temporal.Duration {
const largestUnit: DateUnit = options?.largestUnit ?? 'days';
if (largestUnit === 'years' || largestUnit === 'year') {
const h1 = this.toHijri(one);
const h2 = this.toHijri(two);
const diff = borrowHijriDiff(this.engine, h2.hy - h1.hy, h2.hm - h1.hm, h2.hd - h1.hd, h2);
return new Temporal.Duration(diff.years, diff.months, 0, diff.days);
}
if (largestUnit === 'months' || largestUnit === 'month') {
const h1 = this.toHijri(one);
const h2 = this.toHijri(two);
const diff = borrowHijriDiff(this.engine, h2.hy - h1.hy, h2.hm - h1.hm, h2.hd - h1.hd, h2);
// Roll years into months.
return new Temporal.Duration(0, diff.years * 12 + diff.months, 0, diff.days);
}
// For weeks and days, delegate to ISO arithmetic which is exact.
if (largestUnit === 'weeks' || largestUnit === 'week') {
return one.until(two, { largestUnit: 'weeks' });
}
return one.until(two, { largestUnit: 'days' });
}
mergeFields(
fields: Record<string, unknown>,
additionalFields: Record<string, unknown>,
): Record<string, unknown> {
return { ...fields, ...additionalFields };
}
}
|