bizdays-toolkit 0.32.6 → 0.32.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -6,6 +6,15 @@ Entries from 0.31.0 are in English. Earlier entries remain in Japanese (their **
6
6
 
7
7
  ## [Unreleased]
8
8
 
9
+ ## [0.32.7] - 2026-11-21
10
+
11
+ ### Changed
12
+
13
+ - The option diagnostics of a schedule are faster when a business-day rule counts on a calendar with a holiday provider and the scan reaches years outside the provider's supported years (for example, a schedule without a provider counting on the Japanese holiday calendar). A month in which that calendar throws is now evaluated once per rule in a diagnosis, instead of every time the scan looks at it. On the maintainer's machine, such a schedule is diagnosed in about 40% of the time of 0.32.6. Results, exceptions and diagnostics are unchanged
14
+ - Judging days and the option diagnostics are faster: a date that was just converted to a day number (or built from one) is not parsed again, and the rules for the nth business day of a week, the days before and after holidays (`dayBeforeHoliday`, `dayAfterHoliday`) and holiday shifts (`holidayOverlapPolicy: "after-holiday"`) step through day numbers instead of building date strings. On the maintainer's machine, calling `isBusinessDay` or `valueOn` for the days of 2020–2029 in random order takes about 85–100% of the time of 0.32.6 depending on the settings (about 85–90% for a calendar with a holiday-shift rule and for `valueOn`; for a store calendar without such rules the difference was sometimes not measurable; measured alternately with 0.32.6 in one process), and, together with the change above, diagnosing a schedule counted on the Japanese holiday calendar takes about 30% of the time of 0.32.6. Results, exceptions and diagnostics are unchanged
15
+ - Creating a calendar or a schedule, and `toDateString`, are faster when the time zone is a name the runtime returned (for example the time zone of a holiday provider): the name is no longer normalized again on every call. On the maintainer's machine, `createCalendar({ holidayProvider: jp, closedWeekdays: [0] })` takes about 80–85% of the time of 0.32.6. Results are unchanged
16
+ - Judging days of a calendar or a schedule with many individual dates (`closedDates`, `openDates`, `dates`) is faster when no two of them overlap: the dates are looked up by binary search in start order, instead of being checked one by one for every day. Dates already written in start order are used as they are; otherwise they are sorted once the number of judgments reaches about twice the base-2 logarithm of the number of dates (for example, 18 judgments for 500 dates), so creating a calendar and judging only a few days does not pay for sorting. When some dates overlap, they are still checked in the order written, so the entry written first still decides. On the maintainer's machine (measured alternately with 0.32.6 in one process), `diffBusinessDays` over one year for a calendar with 500 closed dates takes about 30% of the time of 0.32.6, diagnosing a schedule counted on a calendar with 300 closed dates about 35%, and creating a calendar with 100–2,000 closed dates in mixed order and judging one day about the same time (100–106%). When the dates are not written in start order, creating a calendar and judging a few dozen days, around the point where the dates get sorted, can take up to about 20% longer than 0.32.6 (for example, about 25 days for 2,000 dates, or about 8 days for 10 dates); judging fewer days takes about the same time, and judging more days is faster. Results, exceptions and diagnostics are unchanged
17
+
9
18
  ## [0.32.6] - 2026-11-20
10
19
 
11
20
  ### Fixed
@@ -1044,7 +1053,8 @@ This version rebuilds the `redundant` diagnostic so that the reported rules can
1044
1053
 
1045
1054
  - 日本: 2026 年 2 月の官報(2027 年の春分・秋分の日)まで反映(`dataVersion: "2026-02"`、`confirmedThrough: 2027`)
1046
1055
 
1047
- [Unreleased]: https://github.com/inohan77/bizdays-toolkit/compare/v0.32.6...HEAD
1056
+ [Unreleased]: https://github.com/inohan77/bizdays-toolkit/compare/v0.32.7...HEAD
1057
+ [0.32.7]: https://github.com/inohan77/bizdays-toolkit/compare/v0.32.6...v0.32.7
1048
1058
  [0.32.6]: https://github.com/inohan77/bizdays-toolkit/compare/v0.32.5...v0.32.6
1049
1059
  [0.32.5]: https://github.com/inohan77/bizdays-toolkit/compare/v0.32.4...v0.32.5
1050
1060
  [0.32.4]: https://github.com/inohan77/bizdays-toolkit/compare/v0.32.3...v0.32.4
@@ -1,10 +1,10 @@
1
- import { addDays, lengthOfMonth, formatDate, fromDayNumber, toDayNumber, } from "./date.js";
1
+ import { addDays, lengthOfMonth, formatDate } from "./date.js";
2
2
  import { checkUnknownKeys, internalError, IssueCollector, describeValue, rangeError, withoutUndefined, } from "./errors.js";
3
3
  import { isOptionsObject } from "./options.js";
4
4
  import { renameKeys, writtenKey } from "./renamed.js";
5
5
  import { distinctTimeZones, parseTimeOfDaySeconds, toCivil } from "./input.js";
6
6
  import { checkClosingDay, closingDayIn, closingMonth as calendarClosingMonth, dayOfMonth, formatMonth, isDayOfMonthValue, parseMonth, readsAsDate, shiftMonth, } from "./month.js";
7
- import { buildSchedule, compileAnnualRules, compileDateRules, compileHolidaySource, compileRecurringRules, createHolidayLookup, infoOfSchedule, PARTS, partsHolder, partsOf, valuesOfSchedule, isWeekday, mapDays, RECURRING_RULE_KEYS, jpUsage, } from "./schedule.js";
7
+ import { buildSchedule, compileAnnualRules, compileDateRules, compileHolidaySource, compileRecurringRules, createHolidayLookup, infoOfSchedule, PARTS, partsHolder, partsOf, valuesOfSchedule, isWeekday, mapDays, RECURRING_RULE_KEYS, jpUsage, dateOfDayNumber, dayNumberOf, } from "./schedule.js";
8
8
  export const CALENDAR_OPTION_KEYS = [
9
9
  "holidayProvider",
10
10
  "timeZone",
@@ -128,9 +128,9 @@ function dayInfoFromScheduleDay(day, open, fromSchedule) {
128
128
  function buildCalendar(lookup, isOpen, info, searchDayLimit) {
129
129
  const dateOf = lookup.dateOf;
130
130
  function search(start, step, open = true) {
131
- let n = toDayNumber(start);
131
+ let n = dayNumberOf(start);
132
132
  for (let i = 0; i < searchDayLimit; i++, n += step) {
133
- const date = fromDayNumber(n);
133
+ const date = dateOfDayNumber(n);
134
134
  if (isOpen(date) === open)
135
135
  return date;
136
136
  }
@@ -144,7 +144,7 @@ function buildCalendar(lookup, isOpen, info, searchDayLimit) {
144
144
  function countOpen(from, toExclusive) {
145
145
  let count = 0;
146
146
  for (let n = from; n < toExclusive; n++)
147
- if (isOpen(fromDayNumber(n)))
147
+ if (isOpen(dateOfDayNumber(n)))
148
148
  count++;
149
149
  return count;
150
150
  }
@@ -189,13 +189,13 @@ function buildCalendar(lookup, isOpen, info, searchDayLimit) {
189
189
  }
190
190
  function searchInMonth(start, step, limited) {
191
191
  const { year, month } = parseMonth(start.slice(0, 7));
192
- const first = toDayNumber(formatDate(year, month, 1));
192
+ const first = dayNumberOf(formatDate(year, month, 1));
193
193
  const last = first + lengthOfMonth(year, month) - 1;
194
- let n = toDayNumber(start);
194
+ let n = dayNumberOf(start);
195
195
  for (let i = 0; n >= first && n <= last; i++, n += step) {
196
196
  if (limited && i >= searchDayLimit)
197
197
  throw noBusinessDay(start);
198
- const date = fromDayNumber(n);
198
+ const date = dateOfDayNumber(n);
199
199
  if (isOpen(date))
200
200
  return date;
201
201
  }
@@ -276,8 +276,8 @@ function buildCalendar(lookup, isOpen, info, searchDayLimit) {
276
276
  return date;
277
277
  },
278
278
  diffBusinessDays(from, to) {
279
- const a = toDayNumber(dateOf(from));
280
- const b = toDayNumber(dateOf(to));
279
+ const a = dayNumberOf(dateOf(from));
280
+ const b = dayNumberOf(dateOf(to));
281
281
  return a <= b ? countOpen(a, b) : 0 - countOpen(b, a);
282
282
  },
283
283
  businessDatesBetween(from, to) {
@@ -286,8 +286,8 @@ function buildCalendar(lookup, isOpen, info, searchDayLimit) {
286
286
  if (a > b)
287
287
  throw rangeError("invalid-range", `"from" must not be after "to" (${a} > ${b})`);
288
288
  const result = [];
289
- for (let n = toDayNumber(a); n <= toDayNumber(b); n++) {
290
- const date = fromDayNumber(n);
289
+ for (let n = dayNumberOf(a); n <= dayNumberOf(b); n++) {
290
+ const date = dateOfDayNumber(n);
291
291
  if (isOpen(date))
292
292
  result.push(date);
293
293
  }
@@ -1,9 +1,9 @@
1
- import { formatDate, lengthOfMonth, fromDayNumber, isValidDate, parseDate, toDayNumber, weekdayOf, } from "./date.js";
1
+ import { formatDate, lengthOfMonth, isValidDate, parseDate, weekdayOf, } from "./date.js";
2
2
  import { compileCalendarOptions } from "./calendar.js";
3
3
  import { internalError, InternalError, describeValue, IssueCollector, rangeError, } from "./errors.js";
4
4
  import { isOptionsObject } from "./options.js";
5
5
  import { RENAMED_KEYS, RENAMED_VALUES } from "./renamed.js";
6
- import { compileScheduleOptions, createBasis, createHolidayLookup, createResolver, lostShiftMessage, throwLostShift, inPeriod, MAX_HOLIDAY_RUN, jpUsage, matchMonthDay, matchPattern, partsOf, isHolidayBasedRule, resultIgnoresHolidays, } from "./schedule.js";
6
+ import { compileScheduleOptions, createBasis, createHolidayLookup, createResolver, lostShiftMessage, throwLostShift, inPeriod, MAX_HOLIDAY_RUN, jpUsage, matchMonthDay, matchPattern, partsOf, isHolidayBasedRule, resultIgnoresHolidays, dateOfDayNumber, dayNumberOf, } from "./schedule.js";
7
7
  function editDistance(a, b) {
8
8
  const d = Array.from({ length: a.length + 1 }, (_, i) => Array.from({ length: b.length + 1 }, (_, j) => (i === 0 ? j : j === 0 ? i : 0)));
9
9
  for (let i = 1; i <= a.length; i++) {
@@ -45,10 +45,10 @@ function closestOf(key, known) {
45
45
  }
46
46
  return best;
47
47
  }
48
- const PATTERN_FROM = toDayNumber("2001-01-01");
49
- const PATTERN_DAYS = toDayNumber("2028-12-31") - PATTERN_FROM + 1;
50
- const MIN_DAY = toDayNumber("1000-01-01");
51
- const MAX_DAY = toDayNumber("9999-12-31");
48
+ const PATTERN_FROM = dayNumberOf("2001-01-01");
49
+ const PATTERN_DAYS = dayNumberOf("2028-12-31") - PATTERN_FROM + 1;
50
+ const MIN_DAY = dayNumberOf("1000-01-01");
51
+ const MAX_DAY = dayNumberOf("9999-12-31");
52
52
  const MAX_WINDOW_YEARS = 200;
53
53
  const MAX_DATE_RULE_DAYS = 366 * MAX_WINDOW_YEARS;
54
54
  const isLostShift = (error) => error?.code === "holiday-run-too-long";
@@ -64,17 +64,18 @@ const atEdge = (n, error, window) => {
64
64
  const last = window.ranges[window.ranges.length - 1].to;
65
65
  return n < first + PROVIDER_EDGE_DAYS || n > last - PROVIDER_EDGE_DAYS;
66
66
  };
67
- function openEndedDays(from, days) {
67
+ function crossesShortCentury(from, to) {
68
68
  const lo = Math.max(from, MIN_DAY);
69
- const hi = Math.min(from + days - 1, MAX_DAY);
69
+ const hi = Math.min(to, MAX_DAY);
70
70
  if (lo > hi)
71
- return days;
71
+ return false;
72
72
  const last = yearOf(hi);
73
73
  for (let y = Math.ceil(yearOf(lo) / 100) * 100; y <= last; y += 100)
74
74
  if (y % 400 !== 0)
75
- return Math.max(days, 2 * PATTERN_DAYS);
76
- return days;
75
+ return true;
76
+ return false;
77
77
  }
78
+ const openEndedDays = (from, days) => crossesShortCentury(from, from + days - 1) ? Math.max(days, 2 * PATTERN_DAYS) : days;
78
79
  function periodSpan(rule, cycle) {
79
80
  const { effectiveFrom, effectiveTo } = rule;
80
81
  if (effectiveFrom === null) {
@@ -107,7 +108,7 @@ function clipYears(from, to) {
107
108
  const b = Math.min(to, 2099);
108
109
  return a <= b ? [a, b] : [from, from + MAX_WINDOW_YEARS - 1];
109
110
  }
110
- const dayOfYear = (year, last) => toDayNumber(`${String(year).padStart(4, "0")}-${last ? "12-31" : "01-01"}`);
111
+ const dayOfYear = (year, last) => dayNumberOf(`${String(year).padStart(4, "0")}-${last ? "12-31" : "01-01"}`);
111
112
  function collectBasis(calendar, inside) {
112
113
  const parts = partsOf(calendar);
113
114
  if (parts === undefined)
@@ -131,13 +132,6 @@ function collectBasis(calendar, inside) {
131
132
  inside.rules.push(...recurring);
132
133
  return recurring.every((r) => r.calendar === null || collectBasis(r.calendar, inside));
133
134
  }
134
- const crossesShortCentury = ({ from, to }) => {
135
- const last = yearOf(Math.min(to, MAX_DAY));
136
- for (let y = Math.ceil(yearOf(Math.max(from, MIN_DAY)) / 100) * 100; y <= last; y += 100)
137
- if (y % 400 !== 0)
138
- return true;
139
- return false;
140
- };
141
135
  function scanWindow(source, rules, cycle, inside) {
142
136
  const ranges = [];
143
137
  const side = (day, before) => before
@@ -201,7 +195,7 @@ function scanWindow(source, rules, cycle, inside) {
201
195
  else
202
196
  merged.push(r);
203
197
  }
204
- const yearOf = (n) => parseDate(fromDayNumber(n)).year;
198
+ const yearOf = (n) => parseDate(dateOfDayNumber(n)).year;
205
199
  const label = merged.map((r) => `${yearOf(r.from)}-${yearOf(r.to)}`).join(", ");
206
200
  return { ranges: merged, label, blind: false };
207
201
  }
@@ -221,7 +215,7 @@ export function rulesScanWindow(compiled) {
221
215
  (cycle >= max && own < max) ||
222
216
  days > MAX_SCAN_DAYS ||
223
217
  (inside.rules.some((r) => r.interval !== null || r.cycle !== null) &&
224
- window.ranges.some(crossesShortCentury));
218
+ window.ranges.some((r) => crossesShortCentury(r.from, r.to)));
225
219
  if (!blind)
226
220
  return window;
227
221
  return { ...(known ? scanWindow(source, rules, own) : window), blind };
@@ -237,7 +231,7 @@ function patternBits(rule) {
237
231
  const bits = new Uint8Array(PATTERN_DAYS);
238
232
  const weekly = rule.interval === null ? rule : { ...rule, interval: null, anchor: null };
239
233
  for (let i = 0; i < PATTERN_DAYS; i++) {
240
- if (matchPattern(weekly, fromDayNumber(PATTERN_FROM + i)))
234
+ if (matchPattern(weekly, dateOfDayNumber(PATTERN_FROM + i)))
241
235
  bits[i] = 1;
242
236
  }
243
237
  return bits;
@@ -250,7 +244,7 @@ function matchesAnyDay(rule, cycle) {
250
244
  ? Math.min(span.to, span.from + openEndedDays(span.from, cycle) - 1)
251
245
  : span.to;
252
246
  for (let n = Math.max(span.from, MIN_DAY); n <= Math.min(to, MAX_DAY); n++)
253
- if (matchPattern(rule, fromDayNumber(n)))
247
+ if (matchPattern(rule, dateOfDayNumber(n)))
254
248
  return true;
255
249
  return false;
256
250
  }
@@ -344,7 +338,7 @@ function sameValueIn(a, b, seen) {
344
338
  ka.every((k) => Object.hasOwn(b, k) &&
345
339
  sameValueIn(a[k], b[k], seen)));
346
340
  }
347
- const yearOf = (dayNumber) => parseDate(fromDayNumber(dayNumber)).year;
341
+ const yearOf = (dayNumber) => parseDate(dateOfDayNumber(dayNumber)).year;
348
342
  function without(compiled, rule, dropDates) {
349
343
  return {
350
344
  ...compiled,
@@ -387,16 +381,21 @@ function guardBases(compiled, unknownMonths) {
387
381
  const basis = r.basis;
388
382
  if (basis === null || r.calendar === null)
389
383
  return r;
384
+ const thrown = new Set();
390
385
  return {
391
386
  ...r,
392
387
  basis: (year, month) => {
388
+ const m = year * 12 + month - 1;
389
+ if (thrown.has(m))
390
+ return [];
393
391
  try {
394
392
  return basis(year, month);
395
393
  }
396
394
  catch (error) {
397
395
  if (!UNJUDGEABLE.has(String(error.code)))
398
396
  throw error;
399
- unknownMonths.add(year * 12 + month - 1);
397
+ unknownMonths.add(m);
398
+ thrown.add(m);
400
399
  return [];
401
400
  }
402
401
  },
@@ -412,8 +411,12 @@ export function unjudgeableDays(compiled, window) {
412
411
  if (!window || bases.length === 0)
413
412
  return { days, months };
414
413
  const monthOf = (day) => {
415
- const { year, month } = parseDate(fromDayNumber(day));
416
- return year * 12 + month - 1;
414
+ if (day < MIN_DAY || day > MAX_DAY) {
415
+ const { year, month } = parseDate(dateOfDayNumber(day));
416
+ return year * 12 + month - 1;
417
+ }
418
+ const d = new Date(day * 86_400_000);
419
+ return d.getUTCFullYear() * 12 + d.getUTCMonth();
417
420
  };
418
421
  for (const r of bases) {
419
422
  const thrown = new Map();
@@ -440,12 +443,14 @@ export function unjudgeableDays(compiled, window) {
440
443
  if (from > to)
441
444
  continue;
442
445
  if (r.weekStart === null) {
443
- for (let n = from; n <= to; n++)
444
- if (inMonths(monthOf(n)) && throws(monthOf(n)))
446
+ for (let n = from; n <= to; n++) {
447
+ const m = monthOf(n);
448
+ if (inMonths(m) && throws(m))
445
449
  days.add(n);
450
+ }
446
451
  continue;
447
452
  }
448
- const start = from - ((weekdayOf(fromDayNumber(from)) - r.weekStart + 7) % 7);
453
+ const start = from - ((weekdayOf(dateOfDayNumber(from)) - r.weekStart + 7) % 7);
449
454
  for (let w = start; w <= to; w += 7) {
450
455
  const all = [0, 1, 2, 3, 4, 5, 6].map((i) => w + i);
451
456
  const week = all.filter((n) => n >= MIN_DAY && n <= MAX_DAY);
@@ -522,7 +527,7 @@ function checkLostShifts(c, compiled, lookup, window) {
522
527
  const days = [];
523
528
  for (let y = yearOf(from); y <= yearOf(to); y++)
524
529
  for (const h of lookup.holidaysInYear(y))
525
- days.push(toDayNumber(h.date));
530
+ days.push(dayNumberOf(h.date));
526
531
  for (let i = 0; i < days.length; i++) {
527
532
  const back = MAX_HOLIDAY_RUN - 1;
528
533
  if (!skipping && days[i - back] !== days[i] - back)
@@ -530,7 +535,7 @@ function checkLostShifts(c, compiled, lookup, window) {
530
535
  const last = Math.min(days[i] + 7, (days[i + 1] ?? Infinity) - 1, to, MAX_DAY);
531
536
  for (let n = days[i] + 1; n <= last; n++) {
532
537
  try {
533
- resolve(fromDayNumber(n), false);
538
+ resolve(dateOfDayNumber(n), false);
534
539
  }
535
540
  catch (error) {
536
541
  if (!atEdge(n, error, window))
@@ -637,7 +642,7 @@ function analyzeRules(c, compiled, isCalendar, unsure = () => false) {
637
642
  if (!inPeriod(rule, n))
638
643
  return false;
639
644
  try {
640
- found = matchPattern(rule, fromDayNumber(n), holidayOfSafe, undefined, lookup.fromJp);
645
+ found = matchPattern(rule, dateOfDayNumber(n), holidayOfSafe, undefined, lookup.fromJp);
641
646
  }
642
647
  catch (error) {
643
648
  if (!atCalendarEdge(n, error))
@@ -656,7 +661,7 @@ function analyzeRules(c, compiled, isCalendar, unsure = () => false) {
656
661
  if (!inPeriod(rule, n))
657
662
  return false;
658
663
  try {
659
- found = matchPattern(rule, fromDayNumber(n), holidayOfSafe, basis, lookup.fromJp);
664
+ found = matchPattern(rule, dateOfDayNumber(n), holidayOfSafe, basis, lookup.fromJp);
660
665
  }
661
666
  catch {
662
667
  found = false;
@@ -674,7 +679,7 @@ function analyzeRules(c, compiled, isCalendar, unsure = () => false) {
674
679
  if (nationalAsRegular === undefined) {
675
680
  let found = false;
676
681
  if (window && jpUsage(source) === "only") {
677
- eachDay(window, (n) => (found = holidayOfSafe(fromDayNumber(n))?.kind === renamedKind.from));
682
+ eachDay(window, (n) => (found = holidayOfSafe(dateOfDayNumber(n))?.kind === renamedKind.from));
678
683
  nationalAsRegular = !found;
679
684
  }
680
685
  else
@@ -789,7 +794,7 @@ function analyzeRules(c, compiled, isCalendar, unsure = () => false) {
789
794
  let found = false;
790
795
  eachDay(window, (n) => {
791
796
  try {
792
- found = resolve(fromDayNumber(n)).day.value === true;
797
+ found = resolve(dateOfDayNumber(n)).day.value === true;
793
798
  }
794
799
  catch (error) {
795
800
  if (!atEdge(n, error, window) && !isLostShift(error))
@@ -813,12 +818,12 @@ function analyzeRules(c, compiled, isCalendar, unsure = () => false) {
813
818
  for (const n of days) {
814
819
  out.add(n);
815
820
  if (countsMonth) {
816
- const { year, month, day } = parseDate(fromDayNumber(n));
821
+ const { year, month, day } = parseDate(dateOfDayNumber(n));
817
822
  for (let k = 0; k < lengthOfMonth(year, month); k++)
818
823
  out.add(n - day + 1 + k);
819
824
  }
820
825
  for (const start of weekStarts) {
821
- const first = n - ((weekdayOf(fromDayNumber(n)) - start + 7) % 7);
826
+ const first = n - ((weekdayOf(dateOfDayNumber(n)) - start + 7) % 7);
822
827
  for (let k = 0; k < 7; k++)
823
828
  out.add(first + k);
824
829
  }
@@ -832,7 +837,7 @@ function analyzeRules(c, compiled, isCalendar, unsure = () => false) {
832
837
  if (!values.has(n)) {
833
838
  let value;
834
839
  try {
835
- value = resolve(fromDayNumber(n)).day.value;
840
+ value = resolve(dateOfDayNumber(n)).day.value;
836
841
  }
837
842
  catch {
838
843
  value = FAILED;
@@ -847,7 +852,7 @@ function analyzeRules(c, compiled, isCalendar, unsure = () => false) {
847
852
  for (const n of days) {
848
853
  let value;
849
854
  try {
850
- value = resolve(fromDayNumber(n)).day.value;
855
+ value = resolve(dateOfDayNumber(n)).day.value;
851
856
  }
852
857
  catch {
853
858
  value = FAILED;
@@ -883,7 +888,7 @@ function analyzeRules(c, compiled, isCalendar, unsure = () => false) {
883
888
  span.push(n);
884
889
  let decidedBy;
885
890
  try {
886
- decidedBy = resolve(fromDayNumber(n)).rule;
891
+ decidedBy = resolve(dateOfDayNumber(n)).rule;
887
892
  }
888
893
  catch {
889
894
  continue;
@@ -919,7 +924,7 @@ function analyzeRules(c, compiled, isCalendar, unsure = () => false) {
919
924
  eachDay(window, (n) => {
920
925
  let by;
921
926
  try {
922
- by = resolveNow(fromDayNumber(n)).rule;
927
+ by = resolveNow(dateOfDayNumber(n)).rule;
923
928
  }
924
929
  catch {
925
930
  unjudged.add(n);
@@ -941,7 +946,7 @@ function analyzeRules(c, compiled, isCalendar, unsure = () => false) {
941
946
  continue;
942
947
  for (const days of decided.values())
943
948
  days.delete(n);
944
- const by = resolveNow(fromDayNumber(n)).rule;
949
+ const by = resolveNow(dateOfDayNumber(n)).rule;
945
950
  if (by)
946
951
  decided.get(by)?.add(n);
947
952
  }
@@ -955,7 +960,7 @@ function analyzeRules(c, compiled, isCalendar, unsure = () => false) {
955
960
  const matched = [];
956
961
  if (window)
957
962
  eachDay(window, (n) => {
958
- if (matchMonthDay(rule, fromDayNumber(n).slice(5)))
963
+ if (matchMonthDay(rule, dateOfDayNumber(n).slice(5)))
959
964
  matched.push(n);
960
965
  });
961
966
  const units = countingUnits(matched);
@@ -1014,7 +1019,7 @@ function analyzeRules(c, compiled, isCalendar, unsure = () => false) {
1014
1019
  const paths = new Set();
1015
1020
  for (const n of days) {
1016
1021
  try {
1017
- paths.add(resolveFinal(fromDayNumber(n)).rule?.path ?? null);
1022
+ paths.add(resolveFinal(dateOfDayNumber(n)).rule?.path ?? null);
1018
1023
  }
1019
1024
  catch {
1020
1025
  paths.add(null);
@@ -1041,13 +1046,13 @@ function compileDiagnoseOptions(options) {
1041
1046
  if (!isValidDate(asOf)) {
1042
1047
  throw rangeError("invalid-date", `asOf must be a date string "YYYY-MM-DD": ${describeValue(asOf)}`);
1043
1048
  }
1044
- return { asOf: toDayNumber(asOf) };
1049
+ return { asOf: dayNumberOf(asOf) };
1045
1050
  }
1046
1051
  function checkExpired(c, compiled, asOf) {
1047
1052
  const ended = (path, last, what, reach = last, why = "") => {
1048
1053
  if (reach < asOf) {
1049
- const until = reach > last ? ` (it could affect results until ${fromDayNumber(reach)}: ${why})` : "";
1050
- c.info("expired", path, `This ${what} ended on ${fromDayNumber(last)}${until}, before ${fromDayNumber(asOf)}; it no longer affects results and can be removed if the past need not be reproduced`);
1054
+ const until = reach > last ? ` (it could affect results until ${dateOfDayNumber(reach)}: ${why})` : "";
1055
+ c.info("expired", path, `This ${what} ended on ${dateOfDayNumber(last)}${until}, before ${dateOfDayNumber(asOf)}; it no longer affects results and can be removed if the past need not be reproduced`);
1051
1056
  }
1052
1057
  };
1053
1058
  const counting = compiled.recurring.filter((r) => r.businessDays !== null && r.basis === null);
@@ -1056,8 +1061,8 @@ function checkExpired(c, compiled, asOf) {
1056
1061
  const countedReach = (last) => {
1057
1062
  let reach = last;
1058
1063
  if (byMonth) {
1059
- const { year, month } = parseDate(fromDayNumber(last));
1060
- reach = toDayNumber(formatDate(year, month, lengthOfMonth(year, month)));
1064
+ const { year, month } = parseDate(dateOfDayNumber(last));
1065
+ reach = dayNumberOf(formatDate(year, month, lengthOfMonth(year, month)));
1061
1066
  }
1062
1067
  return byWeek ? Math.max(reach, last + 6) : reach;
1063
1068
  };
@@ -21,6 +21,8 @@ function formatterFor(timeZone) {
21
21
  return f;
22
22
  }
23
23
  function zoneNameOf(timeZone) {
24
+ if (zoneNames.get(timeZone) === timeZone)
25
+ return timeZone;
24
26
  const key = timeZone.replace(/[A-Z]+/g, (s) => s.toLowerCase());
25
27
  let name = zoneNames.get(key);
26
28
  if (name === undefined) {
@@ -64,7 +66,7 @@ export function distinctTimeZones(zones) {
64
66
  return out;
65
67
  }
66
68
  function wallParts(epochMilliseconds, timeZone) {
67
- const zone = zoneNames.get(timeZone) === timeZone ? timeZone : zoneNameOf(timeZone);
69
+ const zone = zoneNameOf(timeZone);
68
70
  const offset = OFFSET_ZONE_RE.exec(zone);
69
71
  const parts = formatterFor(offset ? "UTC" : zone).formatToParts(new Date(epochMilliseconds +
70
72
  (offset
@@ -1,10 +1,27 @@
1
- import { addDays, lengthOfMonth, formatDate, fromDayNumber, isValidDate, parseDate, toDayNumber, weekdayOf, } from "./date.js";
1
+ import { lengthOfMonth, formatDate, fromDayNumber, isValidDate, parseDate, toDayNumber, } from "./date.js";
2
2
  import { checkUnknownKeys, describeValue, IssueCollector, rangeError, withoutUndefined, } from "./errors.js";
3
3
  import { isOptionsObject } from "./options.js";
4
4
  import { checkNames } from "./names.js";
5
5
  import { RENAMED_VALUES, renameKeys, renameValue, writtenKey } from "./renamed.js";
6
6
  import { distinctTimeZones, instantToCivil, isDate, sameTimeZone, toCivil, toDateTimeParts, toInstant, validateTimeZone, } from "./input.js";
7
7
  import { HOLIDAY_KEY_PATTERN } from "./types.js";
8
+ let memoDate = "1970-01-01";
9
+ let memoDay = 0;
10
+ export function dayNumberOf(date) {
11
+ if (date !== memoDate) {
12
+ memoDay = toDayNumber(date);
13
+ memoDate = date;
14
+ }
15
+ return memoDay;
16
+ }
17
+ export function dateOfDayNumber(dayNumber) {
18
+ const date = fromDayNumber(dayNumber);
19
+ memoDate = date;
20
+ memoDay = Math.floor(dayNumber);
21
+ return date;
22
+ }
23
+ const weekdayOfDayNumber = (dayNumber) => ((((dayNumber + 4) % 7) + 7) % 7);
24
+ const weekdayOfDate = (date) => weekdayOfDayNumber(dayNumberOf(date));
8
25
  const MONTH_DAY_RE = /^(\d{2})-(\d{2})$/;
9
26
  const MAX_DAYS_IN_MONTH = [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
10
27
  const isObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
@@ -56,7 +73,7 @@ function checkDate(c, path, value) {
56
73
  c.error("invalid-date", path, `Invalid date ${describeValue(value)} (expected YYYY-MM-DD)`);
57
74
  return undefined;
58
75
  }
59
- return toDayNumber(value);
76
+ return dayNumberOf(value);
60
77
  }
61
78
  function checkMonthDay(c, path, value) {
62
79
  if (!isValidMonthDay(value)) {
@@ -179,7 +196,7 @@ export function basisFromPredicate(isOpen) {
179
196
  const list = [];
180
197
  const dim = lengthOfMonth(year, month);
181
198
  for (let d = 1; d <= dim; d++)
182
- if (isOpen(formatDate(year, month, d)))
199
+ if (isOpen(formatDate(year, month, d, true)))
183
200
  list.push(d);
184
201
  days = Object.freeze(list);
185
202
  if (cache.size >= 240)
@@ -296,8 +313,8 @@ export function compileRecurringRules(c, path, entries, valueOf, keys, context,
296
313
  const a = checkDate(c, `${p}.anchor`, entry["anchor"]);
297
314
  if (a === undefined)
298
315
  ok = false;
299
- else if (weekday !== null && weekdayOf(entry["anchor"]) !== weekday) {
300
- c.error("invalid-option", `${p}.anchor`, `must be on the same weekday as "weekday" (${String(entry["anchor"])} is weekday ${weekdayOf(entry["anchor"])})`);
316
+ else if (weekday !== null && weekdayOfDate(entry["anchor"]) !== weekday) {
317
+ c.error("invalid-option", `${p}.anchor`, `must be on the same weekday as "weekday" (${String(entry["anchor"])} is weekday ${weekdayOfDate(entry["anchor"])})`);
301
318
  ok = false;
302
319
  }
303
320
  else
@@ -581,15 +598,15 @@ export function matchPattern(rule, date, holidayOf, basis, fromJp) {
581
598
  if (b === undefined)
582
599
  return false;
583
600
  if (rule.weekStart !== null) {
584
- const start = addDays(date, -((weekdayOf(date) - rule.weekStart + 7) % 7));
601
+ const self = dayNumberOf(date);
602
+ const start = self - ((weekdayOfDayNumber(self) - rule.weekStart + 7) % 7);
585
603
  const week = [];
586
- for (let i = 0; i < 7; i++) {
587
- const d = addDays(start, i);
588
- const at = parseDate(d);
604
+ for (let n = start; n < start + 7; n++) {
605
+ const at = parseDate(dateOfDayNumber(n));
589
606
  if (b(at.year, at.month).includes(at.day))
590
- week.push(d);
607
+ week.push(n);
591
608
  }
592
- const at = week.indexOf(date);
609
+ const at = week.indexOf(self);
593
610
  if (at < 0)
594
611
  return false;
595
612
  return rule.businessDays.has(at + 1) || rule.businessDays.has(at - week.length);
@@ -603,7 +620,7 @@ export function matchPattern(rule, date, holidayOf, basis, fromJp) {
603
620
  if (rule.holiday || rule.dayAfterHoliday || rule.dayBeforeHoliday) {
604
621
  if (holidayOf === undefined)
605
622
  return false;
606
- if (rule.weekdays && !rule.weekdays.has(weekdayOf(date)))
623
+ if (rule.weekdays && !rule.weekdays.has(weekdayOfDate(date)))
607
624
  return false;
608
625
  const selected = (h) => (rule.kinds === null ||
609
626
  rule.kinds.has(h.kind) ||
@@ -614,29 +631,29 @@ export function matchPattern(rule, date, holidayOf, basis, fromJp) {
614
631
  return h !== undefined && selected(h);
615
632
  }
616
633
  const skip = rule.skipWeekdays;
617
- if (holidayOf(date) !== undefined || skip?.has(weekdayOf(date)))
634
+ if (holidayOf(date) !== undefined || skip?.has(weekdayOfDate(date)))
618
635
  return false;
619
636
  const step = rule.dayAfterHoliday ? -1 : 1;
637
+ const self = dayNumberOf(date);
620
638
  for (let k = 1; k <= MAX_HOLIDAY_RUN; k++) {
621
- const next = addDays(date, step * k);
622
- const h = holidayOf(next);
639
+ const h = holidayOf(dateOfDayNumber(self + step * k));
623
640
  if (h !== undefined)
624
641
  return selected(h);
625
- if (!skip?.has(weekdayOf(next)))
642
+ if (!skip?.has(weekdayOfDayNumber(self + step * k)))
626
643
  return false;
627
644
  }
628
645
  return false;
629
646
  }
630
647
  if (rule.cycle !== null) {
631
- const offset = (toDayNumber(date) - rule.anchor) % rule.cycle;
648
+ const offset = (dayNumberOf(date) - rule.anchor) % rule.cycle;
632
649
  return rule.positions.has(((offset + rule.cycle) % rule.cycle) + 1);
633
650
  }
634
651
  const dim = lengthOfMonth(year, month);
635
652
  if (rule.weekday !== null) {
636
- if (weekdayOf(date) !== rule.weekday)
653
+ if (weekdayOfDate(date) !== rule.weekday)
637
654
  return false;
638
655
  if (rule.interval !== null)
639
- return (toDayNumber(date) - rule.anchor) % (7 * rule.interval) === 0;
656
+ return (dayNumberOf(date) - rule.anchor) % (7 * rule.interval) === 0;
640
657
  if (rule.nth === null)
641
658
  return true;
642
659
  return rule.nth.has(Math.ceil(day / 7)) || (rule.nth.has(-1) && day + 7 > dim);
@@ -644,7 +661,7 @@ export function matchPattern(rule, date, holidayOf, basis, fromJp) {
644
661
  return rule.days.has(day) || (rule.days.has(-1) && day === dim);
645
662
  }
646
663
  export function matchRecurring(rule, date, holidayOf, basis, fromJp) {
647
- return inPeriod(rule, toDayNumber(date)) && matchPattern(rule, date, holidayOf, basis, fromJp);
664
+ return inPeriod(rule, dayNumberOf(date)) && matchPattern(rule, date, holidayOf, basis, fromJp);
648
665
  }
649
666
  export function createBasis(compiled, lookup) {
650
667
  if (!compiled.recurring.some((r) => r.businessDays !== null && r.basis === null))
@@ -1016,7 +1033,7 @@ export function matchMonthDay(rule, monthDay) {
1016
1033
  : monthDay >= rule.from || monthDay <= rule.to;
1017
1034
  }
1018
1035
  export function matchAnnual(rule, date) {
1019
- return inPeriod(rule, toDayNumber(date)) && matchMonthDay(rule, date.slice(5));
1036
+ return inPeriod(rule, dayNumberOf(date)) && matchMonthDay(rule, date.slice(5));
1020
1037
  }
1021
1038
  export const isHolidayBasedRule = (rule) => rule.holiday === true || rule.dayAfterHoliday === true || rule.dayBeforeHoliday === true;
1022
1039
  export function resultIgnoresHolidays(compiled) {
@@ -1028,26 +1045,68 @@ export function resultIgnoresHolidays(compiled) {
1028
1045
  export function createResolver(compiled, lookup, onLostShift) {
1029
1046
  const { weekly, holiday: holidayRule, annual, dates, recurring } = compiled;
1030
1047
  const hasShift = recurring.some((r) => r.holidayOverlapPolicy === "after-holiday");
1048
+ let sorted;
1049
+ let lookups = 0;
1050
+ const dateRuleOf = (n) => {
1051
+ if (sorted === undefined) {
1052
+ const count = dates.length;
1053
+ if (lookups++ === 0) {
1054
+ let ordered = 1;
1055
+ while (ordered < count && dates[ordered].from > dates[ordered - 1].to)
1056
+ ordered++;
1057
+ if (ordered >= count)
1058
+ sorted = dates;
1059
+ }
1060
+ else if (lookups > 2 * Math.log2(count + 1)) {
1061
+ const keys = new Float64Array(count);
1062
+ for (let i = 0; i < count; i++)
1063
+ keys[i] = (dates[i].from - MIN_DAY_NUMBER) * count + i;
1064
+ keys.sort();
1065
+ const s = [];
1066
+ for (let i = 0; i < count; i++) {
1067
+ const r = dates[keys[i] % count];
1068
+ if (i > 0 && r.from <= s[i - 1].to)
1069
+ break;
1070
+ s.push(r);
1071
+ }
1072
+ sorted = s.length === count ? s : null;
1073
+ }
1074
+ }
1075
+ if (!sorted)
1076
+ return dates.find((r) => n >= r.from && n <= r.to);
1077
+ let lo = 0;
1078
+ let hi = sorted.length;
1079
+ while (lo < hi) {
1080
+ const mid = (lo + hi) >> 1;
1081
+ if (sorted[mid].from <= n)
1082
+ lo = mid + 1;
1083
+ else
1084
+ hi = mid;
1085
+ }
1086
+ const r = lo > 0 ? sorted[lo - 1] : undefined;
1087
+ return r !== undefined && n <= r.to ? r : undefined;
1088
+ };
1031
1089
  const holidayUnused = resultIgnoresHolidays(compiled);
1032
1090
  const basis = createBasis(compiled, lookup);
1033
1091
  const holidayOfNeighbour = (date) => lookup.holidayOfDate(date);
1034
1092
  const isHolidayOfNeighbour = (date) => holidayOfNeighbour(date) !== undefined;
1035
1093
  function shiftedOrigin(rule, date) {
1094
+ const self = dayNumberOf(date);
1036
1095
  for (let k = 1; k <= MAX_HOLIDAY_RUN; k++) {
1037
- const prev = addDays(date, -k);
1038
- if (!isHolidayOfNeighbour(prev) && !rule.skipWeekdays?.has(weekdayOf(prev)))
1096
+ const prev = dateOfDayNumber(self - k);
1097
+ if (!isHolidayOfNeighbour(prev) && !rule.skipWeekdays?.has(weekdayOfDayNumber(self - k)))
1039
1098
  return undefined;
1040
1099
  if (matchRecurring(rule, prev, holidayOfNeighbour, undefined, lookup.fromJp))
1041
1100
  return prev;
1042
1101
  }
1043
- const first = toDayNumber(date) - MAX_HOLIDAY_RUN_SCAN;
1044
- for (let n = toDayNumber(date) - MAX_HOLIDAY_RUN - 1; n >= MIN_DAY_NUMBER; n--) {
1102
+ const first = self - MAX_HOLIDAY_RUN_SCAN;
1103
+ for (let n = self - MAX_HOLIDAY_RUN - 1; n >= MIN_DAY_NUMBER; n--) {
1045
1104
  if (n < first) {
1046
1105
  onLostShift(rule, date, undefined);
1047
1106
  return undefined;
1048
1107
  }
1049
- const prev = fromDayNumber(n);
1050
- if (!isHolidayOfNeighbour(prev) && !rule.skipWeekdays?.has(weekdayOf(prev)))
1108
+ const prev = dateOfDayNumber(n);
1109
+ if (!isHolidayOfNeighbour(prev) && !rule.skipWeekdays?.has(weekdayOfDayNumber(n)))
1051
1110
  return undefined;
1052
1111
  if (matchRecurring(rule, prev, holidayOfNeighbour, undefined, lookup.fromJp)) {
1053
1112
  onLostShift(rule, date, prev);
@@ -1057,8 +1116,8 @@ export function createResolver(compiled, lookup, onLostShift) {
1057
1116
  return undefined;
1058
1117
  }
1059
1118
  return function resolve(date, withHoliday = true) {
1060
- const dayNumber = toDayNumber(date);
1061
- const weekday = weekdayOf(date);
1119
+ const dayNumber = dayNumberOf(date);
1120
+ const weekday = weekdayOfDate(date);
1062
1121
  const holiday = lookup.holidayOfDate(date, holidayUnused && !withHoliday);
1063
1122
  const make = (value, reason, rule, name, shiftedFrom) => {
1064
1123
  const result = {
@@ -1077,7 +1136,7 @@ export function createResolver(compiled, lookup, onLostShift) {
1077
1136
  result.optionPath = result.rulePath = rule.path;
1078
1137
  return { day: Object.freeze(result), rule };
1079
1138
  };
1080
- const byDate = dates.find((r) => dayNumber >= r.from && dayNumber <= r.to);
1139
+ const byDate = dateRuleOf(dayNumber);
1081
1140
  if (byDate)
1082
1141
  return make(byDate.value, "date", byDate, byDate.name);
1083
1142
  const byAnnual = annual.find((r) => matchAnnual(r, date));
@@ -1117,8 +1176,8 @@ export function mapDays(from, to, fn) {
1117
1176
  throw rangeError("invalid-range", `"from" must not be after "to" (${from} > ${to})`);
1118
1177
  }
1119
1178
  const result = [];
1120
- for (let n = toDayNumber(from); n <= toDayNumber(to); n++)
1121
- result.push(fn(fromDayNumber(n)));
1179
+ for (let n = dayNumberOf(from); n <= dayNumberOf(to); n++)
1180
+ result.push(fn(dateOfDayNumber(n)));
1122
1181
  return Object.freeze(result);
1123
1182
  }
1124
1183
  const INTERNAL_INFO = Symbol("bizdays-toolkit.scheduleInfo");
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "bizdays-toolkit",
3
- "version": "0.32.6",
3
+ "version": "0.32.7",
4
4
  "description": "Holidays, business-day calendar and day-by-day schedules (e.g. store hours) with time zone support. Japanese holidays verified against the Cabinet Office data; UK bank holidays (England, Wales, Scotland, Northern Ireland) verified against GOV.UK and The Gazette; French public holidays (metropole, Alsace-Moselle) verified against data.gouv.fr; Singapore public holidays verified against data.gov.sg. / 祝日と営業日のカレンダー(タイムゾーン対応・日本の祝日は内閣府、英国の bank holidays は GOV.UK と The Gazette、フランスの祝日は data.gouv.fr、シンガポールの祝日は data.gov.sg のデータで全日照合)",
5
5
  "keywords": [
6
6
  "bank-holidays",