Repository navigation
Expand file tree
/
Copy pathrange.js
More file actions
459 lines (411 loc) · 16.1 KB
/
Copy pathrange.js
File metadata and controls
459 lines (411 loc) · 16.1 KB
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
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
import { isPlainObject, isString } from './helpers/utils.js';
import { CalendarDate } from './calendar-date.js';
import { DateTime } from './date-time.js';
import { days, duration, hours } from './duration.js';
import { isDevelopment } from './helpers/environment.js';
import { isUnreadable, loosely, readAs, refuse, refuseType, unreadable } from './helpers/errors.js';
import { isDurationFields } from './helpers/fields.js';
import { epochOf, formatter, intlOptions, textFormat } from './helpers/format.js';
import { IS_DATE_RANGE, IS_DATE_TIME_RANGE, IS_DURATION, IS_RANGE, IS_TIME_RANGE } from './helpers/identity.js';
import { alias, inspect, isTemporalDuration, weekdayNamed, zoneOptions } from './helpers/units.js';
import { cachedText, weekendDays } from './helpers/zones.js';
import { Time } from './time.js';
/*
an interval between two points of the same kind (DateRange, DateTimeRange, TimeRange).
DateRange is closed [start, end] because civil date spans include their final day ('Sep 1 to Sep 7' is 7 days).
DateTimeRange and TimeRange are half-open [start, end) so adjacent bookings or shifts share an endpoint cleanly,
and TimeRange wraps across midnight when end < start
*/
const dayLength = 86_400e9; // 24h in nanoseconds
const raw = {};
class Range {
// brand range
get [IS_RANGE]() {
return true;
}
static [Symbol.hasInstance](value) {
return !!value?.[IS_RANGE];
}
// (start, end, zone), (start, end, { zone, loose }), or (interval, { zone, loose })
constructor(start, end, options) {
const kind = this.constructor.kind;
this.kind = kind;
this.start = start;
this.end = end;
if (options !== raw) {
if (Range.isOptions(end)) {
[end, options] = [undefined, end];
}
const settings = zoneOptions(options);
if (start instanceof Range && end === undefined) {
if (start.kind !== kind) {
const [from, to] = [`${start.kind}Range`, `${kind}Range`];
refuseType('conflictingRanges', `${from} as ${to}`, {
explanation: isDevelopment
? 'cannot pass one range type directly into another range factory. Convert a `DateRange` to a `DateTimeRange` with `.in(zone)`, or build a new range from converted `start` and `end` endpoints'
: 0,
});
}
return start;
}
if (isString(start) && end === undefined) {
[start, end] = Range.#splitInterval(start, kind);
}
this.start = Range.#read(kind, start, undefined, settings);
this.end = Range.#readEnd(kind, end, this.start, settings);
if (kind !== 'time' && this.end.isBefore(this.start)) {
refuse('invalidRange', `${this.start} to ${this.end}`, {
explanation: isDevelopment
? 'range end cannot be earlier than its start. Swap the start and end arguments, or order unknown endpoints with `earliest(a, b)` and `latest(a, b)`'
: 0,
});
}
}
Object.freeze(this);
}
// distinguish trailing options in dateRange('a/b', opts) from a field-bag endpoint like { year, month, day }
static isOptions(value) {
const keys = isPlainObject(value) && Object.keys(value);
return !!keys?.length
&& keys.every((key) => ['loose', 'zone', 'dayFirst', 'locale', 'disambiguation', 'format'].includes(key));
}
// mask bracketed '[America/New_York]' zones before splitting on '/', checking spaced ' - ' / ' to ' first
// so '2026/11/06 - 2026/11/10' stays intact and falling back to '-' / '–' only for plain time ranges
static #splitInterval(text, kind) {
const blanked = text.replace(/\[[^[\]]*\]/g, (zone) => ' '.repeat(zone.length));
const separator = blanked.match(/\s(?:-|–|to)\s/) ?? blanked.match('/')
?? (kind === 'time' ? blanked.match(/[-–]/) : null);
return separator
? [text.slice(0, separator.index), text.slice(separator.index + separator[0].length)]
: [text];
}
// coerce endpoints in start's zone and locale so both ends share one frame of reference
static #read(kind, value, start, options = {}) {
const readOptions = {
...options,
locale: options.locale ?? start?.locale(),
zone: kind === 'datetime' ? (start?.zone ?? options.zone) : options.zone,
};
return kind === 'date'
? new CalendarDate(value, readOptions)
: kind === 'datetime'
? new DateTime(value, readOptions)
: new Time(value, readOptions);
}
// endpoints can also be durations (e.g. start.for('2h')), subtracting 1 day on inclusive DateRanges
static #readEnd(kind, value, start, options) {
let unread;
if (!(value?.[IS_DURATION] || isTemporalDuration(value) || isDurationFields(value))) {
try {
return Range.#read(kind, value, start, options);
}
catch (error) {
if (!(isString(value) || isPlainObject(value)) || !isUnreadable(error)) {
throw error;
}
unread = error;
}
}
let length;
try {
length = duration(value);
}
catch (error) {
// report the point error rather than invalidDuration when neither parser recognizes the input
throw unread ?? error;
}
return kind === 'date' ? start.plus(length).minus(days(1)) : start.plus(length);
}
/*******************************
Reads
*******************************/
isEmpty() {
return this.kind !== 'date' && this.start.equals(this.end);
}
get duration() {
if (this.kind === 'date') {
return this.start.until(this.end.plus(days(1)));
}
return this.#wraps() ? this.start.until(this.end).plus(hours(24)) : this.start.until(this.end);
}
#wraps() {
return this.kind === 'time' && this.end.isBefore(this.start);
}
as(kind) {
return readAs(kind, { duration: () => this.duration });
}
/*******************************
Comparison
*******************************/
contains(value) {
if (value?.[IS_RANGE]) {
const rival = this.#make(this.kind, value);
let holds;
if (this.kind === 'time') {
const [start, end] = Range.#spanOf(this);
holds = Range.#besides(rival).some(([rivalStart, rivalEnd]) => rivalStart >= start && rivalEnd <= end);
}
else {
holds = !rival.start.isBefore(this.start) && !rival.end.isAfter(this.end);
}
return holds && !this.isEmpty() && !rival.isEmpty();
}
return this.#holds(value);
}
#holds(value) {
const at = value?.constructor === this.start.constructor ? value : Range.#read(this.kind, value, this.start);
if (this.#wraps()) {
return !at.isBefore(this.start) || at.isBefore(this.end);
}
if (at.isBefore(this.start)) {
return false;
}
return this.#inclusive() ? !at.isAfter(this.end) : at.isBefore(this.end);
}
#inclusive() {
return this.kind === 'date';
}
overlaps(other) {
const rival = this.#make(this.kind, other);
if (this.#inclusive()) {
return !this.start.isAfter(rival.end) && !rival.start.isAfter(this.end);
}
let hits;
if (this.kind === 'time') {
const [start, end] = Range.#spanOf(this);
hits = Range.#besides(rival).some(([rivalStart, rivalEnd]) => rivalStart < end && start < rivalEnd);
}
else {
hits = this.start.isBefore(rival.end) && rival.start.isBefore(this.end);
}
return hits && !this.isEmpty() && !rival.isEmpty();
}
#make(kind, start, end) {
return !end && start?.[IS_RANGE] && start.kind === kind
? start
: new byKind[kind](start, end, { zone: this.start.zone, locale: this.start.locale() });
}
equals(other) {
const rival = this.#make(this.kind, other);
return this.start.equals(rival.start) && this.end.equals(rival.end);
}
/*******************************
Measure
*******************************/
intersection(other) {
const rival = this.#make(this.kind, other);
if (this.kind === 'time') {
return this.#clockIntersection(rival);
}
if (!this.overlaps(rival)) {
return null;
}
const start = this.start.isAfter(rival.start) ? this.start : rival.start;
const end = this.end.isBefore(rival.end) ? this.end : rival.end;
return this.#make(this.kind, start, end);
}
// two overnight ranges like 22:00..06:00 and 05:00..23:00 overlap twice (05:00..06:00 and 22:00..23:00)
#clockIntersection(rival) {
const [start, end] = Range.#spanOf(this);
const pieces = Range.#besides(rival)
.map(([rivalStart, rivalEnd]) => [Math.max(start, rivalStart), Math.min(end, rivalEnd)])
.filter(([from, to]) => from < to);
if (!pieces.length) {
return null;
}
if (pieces.length > 1) {
refuse('unsupportedIntersection', `${this} with ${rival}`, {
explanation: isDevelopment
? 'these two time ranges wrap around midnight and overlap in two separate windows, which a single `TimeRange` cannot represent. Split the overnight range at midnight and intersect each half separately'
: 0,
});
}
const timeAt = (ns) =>
new Time(new Temporal.PlainTime().add({ nanoseconds: ((ns % dayLength) + dayLength) % dayLength }));
return this.#make('time', timeAt(pieces[0][0]), timeAt(pieces[0][1]));
}
// unwrap circular times onto a linear timeline and test shifts of -24h, 0h, and +24h in #besides()
static #spanOf(range) {
const since = (time) => new Temporal.PlainTime().until(time.toTemporal()).total('nanosecond');
const start = since(range.start);
const end = since(range.end);
return [start, end < start ? end + dayLength : end];
}
static #besides(range) {
const [start, end] = Range.#spanOf(range);
return [-dayLength, 0, dayLength].map((shift) => [start + shift, end + shift]);
}
every(step, name) {
// bare unit names like 'month' mean 1 unit, while strings with digits like '30m' parse as durations
const size = name !== undefined
? duration(step, name)
: isString(step) && !/\d/.test(step)
? duration(1, step)
: duration(step);
if (size.isZero() || size.isNegative()) {
refuse('invalidStep', String(size), {
explanation: isDevelopment ? 'step duration for `every()` and `split()` must be greater than zero' : 0,
});
}
const fields = size.toFields();
const [key, extra] = Object.keys(fields);
// validate step unit against start's kind upfront so empty ranges and TimeRange reject mismatched units immediately
this.start.plus(size);
const each = this.kind === 'time' ? size.total('nanosecond') : 0;
const length = each ? this.duration.total('nanosecond') : Infinity;
const points = [];
// step from start (start + i * size) rather than chaining .plus() so Jan 31 monthly hits Mar 31 instead of sticking on the 28th
for (let i = 0; i * each < length; i++) {
const next = i
? this.start.plus(extra ? size.times(i) : fields[key] * i, extra ? undefined : key)
: this.start;
if (!each && !this.#holds(next)) {
return points;
}
points.push(next);
}
return points;
}
split(step, name) {
const points = this.every(step, name);
return points.map((start, i) => {
const following = points[i + 1];
return new byKind[this.kind](
start,
following ? (this.#inclusive() ? following.minus(1, 'day') : following) : this.end,
raw,
);
});
}
// inclusive DateRange [start, end] becomes half-open [start 00:00, (end + 1d) 00:00) in `zone`
in(zone) {
if (this.kind === 'date') {
return this.#make('datetime', this.start.at('00:00', zone), this.end.plus(days(1)).at('00:00', zone));
}
if (this.kind === 'datetime') {
return new DateTimeRange(this.start.in(zone), this.end.in(zone));
}
return refuse('unsupportedZone', String(this), {
explanation: isDevelopment
? 'a `TimeRange` has no calendar date, so it cannot be placed in a time zone directly. Anchor each end to a date with `.on(day, zone)` on `start` and `end`'
: 0,
});
}
/*******************************
Output
*******************************/
locale(...tag) {
return tag.length
? new byKind[this.kind](this.start.locale(tag[0]), this.end.locale(tag[0]))
: this.start.locale();
}
get text() {
return cachedText(this, this.kind === 'datetime' ? textFormat : undefined);
}
format(spec, locale = this.start.locale()) {
const options = intlOptions(this.kind, spec);
if (!options) {
return `${this.start.format(spec, locale)} – ${this.end.format(spec, locale)}`;
}
// Intl.DateTimeFormat.formatRange() natively formats reversed same-day times (22:00 -> 06:00) as overnight ranges
const point = (end) => epochOf(this.kind, this.kind === 'datetime' ? end.epochMilliseconds : end.toTemporal());
return formatter(this.kind, options, locale, this.start.zone).formatRange(point(this.start), point(this.end));
}
toString() {
return `${this.start}/${this.end}`;
}
toJSON() {
return this.toString();
}
valueOf() {
return refuse('unsupportedComparison', String(this), {
explanation: isDevelopment
? 'ranges cannot be converted to a number for `<`, `>`, or `-`. Read `.duration` to measure length, or use `compare(a, b)` and `equals()` to compare ranges'
: 0,
});
}
// '+' sends hint 'default', which would call valueOf() and throw without this
[Symbol.toPrimitive](hint) {
return hint === 'number' ? this.valueOf() : this.toString();
}
// explicit strings so Node inspect output survives minifier class renaming
[inspect]() {
return `${this.kind === 'date' ? 'Date' : this.kind === 'datetime' ? 'DateTime' : 'Time'}Range(${this.start} ${
this.#inclusive() ? 'through' : 'until'
} ${this.end})`;
}
}
export class DateRange extends Range {
// brand date range
get [IS_DATE_RANGE]() {
return true;
}
static [Symbol.hasInstance](value) {
return !!value?.[IS_DATE_RANGE];
}
static kind = 'date';
*[Symbol.iterator]() {
for (let day = this.start;; day = day.plus(1, 'day')) {
yield day;
if (day.equals(this.end)) {
return;
}
}
}
count(kind = 'days') {
const key = String(kind).trim().toLowerCase().replace(/s$/, '');
const total = this.duration.days;
if (key === 'day') {
return total;
}
const weeks = Math.floor(total / 7);
const extra = total % 7;
const start = this.start.dayOfWeek;
const hits = (day) => weeks + ((day - start + 7) % 7 < extra ? 1 : 0);
if (key === 'weekday' || key === 'weekend') {
const off = weekendDays(this.locale()).reduce((sum, day) => sum + hits(day), 0);
return key === 'weekend' ? off : total - off;
}
const target = weekdayNamed(key);
return target
? hits(target)
: refuse('unknownKind', String(kind), {
explanation: isDevelopment
? "expected 'days', 'weekdays', 'weekends', or a weekday name such as 'mondays'. For other units, use `.duration.total(unit)`"
: 0,
});
}
}
export class DateTimeRange extends Range {
// brand datetime range
get [IS_DATE_TIME_RANGE]() {
return true;
}
static [Symbol.hasInstance](value) {
return !!value?.[IS_DATE_TIME_RANGE];
}
static kind = 'datetime';
}
export class TimeRange extends Range {
// brand time range
get [IS_TIME_RANGE]() {
return true;
}
static [Symbol.hasInstance](value) {
return !!value?.[IS_TIME_RANGE];
}
static kind = 'time';
}
alias(Range, { lang: 'locale', includes: 'contains', splitBy: 'split' });
const byKind = { date: DateRange, datetime: DateTimeRange, time: TimeRange };
const build = (Kind, start, end, options) => {
const settings = Range.isOptions(end) ? end : zoneOptions(options);
const make = () => new Kind(start, end, options);
return settings.loose ? loosely(make, unreadable.range) : make();
};
export const dateRange = (start, end, options) => build(DateRange, start, end, options);
export const datetimeRange = (start, end, options) => build(DateTimeRange, start, end, options);
export const timeRange = (start, end, options) => build(TimeRange, start, end, options);
export const isDateRange = (value) => value instanceof DateRange;
export const isDateTimeRange = (value) => value instanceof DateTimeRange;
export const isTimeRange = (value) => value instanceof TimeRange;