Skip to content

Commit

Permalink
Add polyfill changes for weekOfYear()
Browse files Browse the repository at this point in the history
  • Loading branch information
Aditi-1400 committed Jan 24, 2024
1 parent bdb27bc commit 41db8dc
Showing 1 changed file with 45 additions and 1 deletion.
46 changes: 45 additions & 1 deletion polyfill/lib/calendar.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -459,6 +459,14 @@ function resolveNonLunisolarMonth(calendarDate, overflow = undefined, monthsPerY
return { ...calendarDate, month, monthCode };
}

function weekNumber(calendarHelper, desiredDay, dayOfPeriod, dayOfWeek) {
var periodStartDayOfWeek = (dayOfWeek - calendarHelper.getFirstDayOfWeek() - dayOfPeriod + 1) % 7;
if (periodStartDayOfWeek < 0) periodStartDayOfWeek += 7;
var weekNo = MathFloor((desiredDay + periodStartDayOfWeek - 1) / 7);
if (7 - periodStartDayOfWeek >= calendarHelper.getMinimalDaysInFirstWeek()) ++weekNo;
return weekNo;
}

// Note: other built-in calendars than iso8601 are not part of the Temporal
// proposal for ECMA-262. An implementation of these calendars is present in
// this polyfill in order to validate the Temporal API and to get early feedback
Expand Down Expand Up @@ -1702,6 +1710,12 @@ const helperGregory = ObjectAssign(
if (era === 'bc' || era === 'b') era = 'bce';
if (era === 'ad' || era === 'a') era = 'ce';
return { era, eraYear };
},
getFirstDayOfWeek() {
return 1;
},
getMinimalDaysInFirstWeek() {
return 1;
}
}
);
Expand Down Expand Up @@ -2092,7 +2106,37 @@ const nonIsoGeneralImpl = {
return diffDays + 1;
},
weekOfYear(date) {
return impl['iso8601'].weekOfYear(date);
// Supports only Gregorian calendar; can be updated to add support for other calendars.
// Returns undefined for calendars without a well-defined week calendar system.
if (this.helper.id === 'gregory') {
const dayOfWeek = this.dayOfWeek(date);
const dayOfYear = this.dayOfYear(date);
var relDow = (dayOfWeek + 7 - this.helper.getFirstDayOfWeek()) % 7;
// Assuming the year length is less than 7000 days.
var relDowJan1 = (dayOfWeek - dayOfYear + 7001 - this.helper.getFirstDayOfWeek()) % 7;
var woy = MathFloor((dayOfYear - 1 + relDowJan1) / 7);
if (7 - relDowJan1 >= this.helper.getMinimalDaysInFirstWeek()) {
++woy;
}
if (woy == 0) {
var prevDoy = dayOfYear + this.daysInYear(date.add({ years: -1 }));
woy = weekNumber(this.helper, prevDoy, dayOfYear, dayOfWeek);
} else {
var lastDoy = this.daysInYear(date);
if (dayOfYear >= lastDoy - 5) {
var lastRelDow = (relDow + lastDoy - dayOfYear) % 7;
if (lastRelDow < 0) {
lastRelDow += 7;
}
if (6 - lastRelDow >= this.helper.getMinimalDaysInFirstWeek() && dayOfYear + 7 - relDow > lastDoy) {
woy = 1;
}
}
}
return woy;
} else {
return undefined;
}
},
yearOfWeek(date) {
return impl['iso8601'].yearOfWeek(date);
Expand Down

0 comments on commit 41db8dc

Please sign in to comment.