-
Notifications
You must be signed in to change notification settings - Fork 1
/
interval.js
440 lines (440 loc) · 16.7 KB
/
interval.js
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
"use strict";
var moment = require('moment');
var millisPerSecond = 1000;
var millisPerMinute = millisPerSecond * 60;
var millisPerHour = millisPerMinute * 60;
var millisPerDay = millisPerHour * 24;
var millisPerWeek = millisPerDay * 7;
var millisPerYear = millisPerDay * 365;
var recurrenceRegex = /^R(\d*)/;
var recurrenceIndex = {
repetitions: 1
};
// From https://gist.github.com/philipashlock/8830168
var dateRegex = /^([\+-]?\d{4}(?!\d{2}\b))((-?)((0[1-9]|1[0-2])(\3([12]\d|0[1-9]|3[01]))?|W([0-4]\d|5[0-2])(-?[1-7])?|(00[1-9]|0[1-9]\d|[12]\d{2}|3([0-5]\d|6[1-6])))([T\s]((([01]\d|2[0-3])((:?)[0-5]\d)?|24\:?00)([\.,]\d+(?!:))?)?(\17[0-5]\d([\.,]\d+)?)?([zZ]|([\+-])([01]\d|2[0-3]):?([0-5]\d)?)?)?)?$/;
var durationRegex = /^(R(\d*)?\/)?P(?:(\d+(?:\.\d+)?)?Y)?(?:(\d+(?:\.\d+)?)?M)?(?:(\d+(?:\.\d+)?)?W)?(?:(\d+(?:\.\d+)?)?D)?(?:T(?:(\d+(?:\.\d+)?)?H)?(?:(\d+(?:\.\d+)?)?M)?(?:(\d+(?:\.\d+)?)?S)?)?$/;
var durationIndex = {
hasRecurrence: 0,
repetitionCount: 1,
year: 2,
month: 3,
week: 4,
day: 5,
hour: 6,
minute: 7,
second: 8
};
var rangeDateDateRegex = /^([\+-]?\d{4}(?!\d{2}\b))((-?)((0[1-9]|1[0-2])(\3([12]\d|0[1-9]|3[01]))?|W([0-4]\d|5[0-2])(-?[1-7])?|(00[1-9]|0[1-9]\d|[12]\d{2}|3([0-5]\d|6[1-6])))([T\s]((([01]\d|2[0-3])((:?)[0-5]\d)?|24\:?00)([\.,]\d+(?!:))?)?(\17[0-5]\d([\.,]\d+)?)?([zZ]|([\+-])([01]\d|2[0-3]):?([0-5]\d)?)?)?)?(\/)([\+-]?\d{4}(?!\d{2}\b))((-?)((0[1-9]|1[0-2])(\3([12]\d|0[1-9]|3[01]))?|W([0-4]\d|5[0-2])(-?[1-7])?|(00[1-9]|0[1-9]\d|[12]\d{2}|3([0-5]\d|6[1-6])))([T\s]((([01]\d|2[0-3])((:?)[0-5]\d)?|24\:?00)([\.,]\d+(?!:))?)?(\17[0-5]\d([\.,]\d+)?)?([zZ]|([\+-])([01]\d|2[0-3]):?([0-5]\d)?)?)?)?$/;
var rangeDateDurationRegex = /^(R\d*\/)?([\+-]?\d{4}(?!\d{2}\b))((-?)((0[1-9]|1[0-2])(\4([12]\d|0[1-9]|3[01]))?|W([0-4]\d|5[0-2])(-?[1-7])?|(00[1-9]|0[1-9]\d|[12]\d{2}|3([0-5]\d|6[1-6])))([T\s]((([01]\d|2[0-3])((:?)[0-5]\d)?|24\:?00)([\.,]\d+(?!:))?)?(\18[0-5]\d([\.,]\d+)?)?([zZ]|([\+-])([01]\d|2[0-3]):?([0-5]\d)?)?)?)?(\/)P(?:\d+(?:\.\d+)?Y)?(?:\d+(?:\.\d+)?M)?(?:\d+(?:\.\d+)?W)?(?:\d+(?:\.\d+)?D)?(?:T(?:\d+(?:\.\d+)?H)?(?:\d+(?:\.\d+)?M)?(?:\d+(?:\.\d+)?S)?)?$/;
var rangeDurationDateRegex = /^(R\d*\/)?P(?:\d+(?:\.\d+)?Y)?(?:\d+(?:\.\d+)?M)?(?:\d+(?:\.\d+)?W)?(?:\d+(?:\.\d+)?D)?(?:T(?:\d+(?:\.\d+)?H)?(?:\d+(?:\.\d+)?M)?(?:\d+(?:\.\d+)?S)?)?\/([\+-]?\d{4}(?!\d{2}\b))((-?)((0[1-9]|1[0-2])(\4([12]\d|0[1-9]|3[01]))?|W([0-4]\d|5[0-2])(-?[1-7])?|(00[1-9]|0[1-9]\d|[12]\d{2}|3([0-5]\d|6[1-6])))([T\s]((([01]\d|2[0-3])((:?)[0-5]\d)?|24\:?00)([\.,]\d+(?!:))?)?(\18[0-5]\d([\.,]\d+)?)?([zZ]|([\+-])([01]\d|2[0-3]):?([0-5]\d)?)?)?)?$/;
function isInfinite(s) {
return s.length === 0;
}
function isDuration(s) {
return s[0] === 'P';
}
function isRepeating(s) {
return s[0] === 'R';
}
function isTime(s) {
return moment(s).isValid();
}
var String8601Type;
(function (String8601Type) {
String8601Type[String8601Type["repeating"] = 0] = "repeating";
String8601Type[String8601Type["time"] = 1] = "time";
String8601Type[String8601Type["duration"] = 2] = "duration";
String8601Type[String8601Type["infinite"] = 3] = "infinite";
})(String8601Type || (String8601Type = {}));
function parse8601String(s) {
if (isInfinite(s)) {
return {
type: String8601Type.infinite,
value: null
};
}
else if (isDuration(s)) {
return {
type: String8601Type.duration,
value: moment.duration(s)
};
}
else if (isRepeating(s)) {
var result = recurrenceRegex.exec(s);
return {
type: String8601Type.repeating,
value: typeof result[recurrenceIndex.repetitions] === 'string' ?
parseInt(result[recurrenceIndex.repetitions]) : Number.POSITIVE_INFINITY
};
}
else if (isTime(s)) {
return {
type: String8601Type.time,
value: moment(s).valueOf()
};
}
else {
throw new Error("[" + s + "] Is not a valid part of an ISO8601 time string");
}
}
/**
* Class to describe ISO 8601 time intervals, including the repeating functionality.
*
* The class is primarily backed by moment.js and contains the start, end, duration,
* and number of repetitions found in the ISO8601 string or overridden in the constructor.
* Typical usage of the class is to construct one with a ISO8601 string in the constructor.
*/
var Interval = (function () {
/**
* @param interval either ISO8601 string or an instance to copy
* @param repetitions the number of times to repeat, null for infinite
*/
function Interval(interval, repetitions) {
this._recurs = false;
this._repetitions = 0;
this._infiniteSpan = false;
if (typeof interval === 'string') {
// Parse out the ISO 8601 string
var split = interval.split('/');
if (split.length > 3) {
throw new Error("Invalid ISO 8601 string[" + interval + "]");
}
for (var i = 0; i < split.length; i++) {
var fragment = split[i];
var parsed = parse8601String(fragment);
switch (parsed.type) {
case String8601Type.repeating:
if (i !== 0) {
throw new Error("Incorrect placement of recurrence");
}
if (parsed.value !== 0) {
this._recurs = true;
this._repetitions = parsed.value;
}
break;
case String8601Type.time:
if (this._duration || this._start || this._infiniteSpan) {
this._end = parsed.value;
}
else if (!this._start) {
this._start = parsed.value;
}
else {
throw new Error("Invalid interval[" + interval + "] end time must come after a duration, start time or be an infinite span");
}
break;
case String8601Type.duration:
if (this._duration) {
throw new Error("Invalid interval[" + interval + "] two durations found");
}
this._duration = parsed.value;
break;
case String8601Type.infinite:
if (this._duration || this._recurs) {
throw new Error("Invalid interval[" + interval + "] single span infinite not compatible with durations or recurrence");
}
this._infiniteSpan = true;
break;
default:
throw new Error("Experienced unhandled type");
}
}
}
else {
this._start = interval._start;
this._end = interval._end;
this._duration = moment.duration(interval._duration);
this._recurs = interval._recurs;
this._repetitions = interval._repetitions;
this._infiniteSpan = interval._infiniteSpan;
}
if (typeof repetitions === 'number') {
if (repetitions === 0) {
this._recurs = false;
}
this._repetitions = repetitions;
}
else if (repetitions === null) {
this._recurs = true;
this._repetitions = repetitions;
}
// Throw an error if this this is just bunk
if (this._start && this._end && this._duration) {
throw new Error("Error creating interval with args[" + arguments + "]");
}
// Determine the first and last occurrence indexes
if (!this._recurs) {
// Non recurring case
this._first = 0;
if (this._end || this._duration) {
this._last = 1;
}
else {
this._last = 0;
}
}
else if (this._start && (this._end || this._duration)) {
// Forward progressing case
this._first = 0;
this._last = this._repetitions;
}
else {
// Backward progressing case
this._last = 0;
this._first = -this._repetitions;
}
}
Object.defineProperty(Interval.prototype, "start", {
/**
* The start of all intervals, if this is a repeating interval
* then this is the start of the first repitition.
* Returns an invalid moment if there are infinite negative repetitions
*/
get: function () {
if (this.isInfiniteNegative) {
return moment.invalid();
}
else {
return this.occurrence(this.first);
}
},
enumerable: true,
configurable: true
});
Object.defineProperty(Interval.prototype, "end", {
/**
* The end of all intervals, if this is a repeating interval
* then this is then end of the last repitition.
* Returns an invalid moment if there are infinite positive repetitions
*/
get: function () {
if (this.isInfinitePositive) {
return moment.invalid();
}
else {
return this.occurrence(this.last);
}
},
enumerable: true,
configurable: true
});
Object.defineProperty(Interval.prototype, "duration", {
/**
* The duration of a single repition of the interval
*/
get: function () {
if (this._duration) {
return this._duration;
}
if (this._start && this._end) {
return moment.duration(this._end - this._start);
}
else {
return moment.duration(0);
}
},
enumerable: true,
configurable: true
});
Object.defineProperty(Interval.prototype, "isInfinite", {
/**
* True if the schedule is infintely long
* @returns {boolean}
*/
get: function () {
return !isFinite(this._repetitions) || this._infiniteSpan;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Interval.prototype, "isInfinitePositive", {
/**
* True if the schedule progresses infinitely in the positive
* @returns {boolean}
*/
get: function () {
return !isFinite(this.last) || (this._infiniteSpan && !this._end);
},
enumerable: true,
configurable: true
});
Object.defineProperty(Interval.prototype, "isInfiniteNegative", {
/**
* True if the schedule progresses infinitely in the negative
* @returns {boolean}
*/
get: function () {
return !isFinite(this.first) || (this._infiniteSpan && !this._start);
},
enumerable: true,
configurable: true
});
Object.defineProperty(Interval.prototype, "isRepeating", {
/**
* True if the schedule repeats (has more than one occurrence)
* @returns {boolean}
*/
get: function () {
return this._recurs;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Interval.prototype, "repetitions", {
/**
* The number of repetitions
* @returns {number}
*/
get: function () {
return this._repetitions;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Interval.prototype, "first", {
/**
* Index of the first occurrence,
* Number.NEGATIVE_INFINITY if the interval is reverse repeating indefinitely
* @returns {number}
*/
get: function () {
return this._first;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Interval.prototype, "last", {
/**
* Index of the last occurrence,
* Number.POSITIVE_INFINITY if the interval is forward repeating indefinitely
* @returns {number}
*/
get: function () {
return this._last;
},
enumerable: true,
configurable: true
});
Interval.prototype.occurrence = function (idx) {
if (idx > this.last || idx < this.first) {
return moment.invalid();
}
if (this.isInfiniteNegative) {
return moment(this._end).subtract(this.durationBetween(idx, this.last));
}
else {
return moment(this._start).add(this.durationBetween(this.first, idx));
}
};
/**
* Get a list of the occurrences for an interval,
* if no parameters are supplied then all occurrences are returned.
*
* @param {number} [from] the starting occurrence index
* @param {number} [to] the ending occurrence index
* @returns {moment.Moment[]}
*/
Interval.prototype.slice = function (from, to) {
// Check for being out of bounds
if (from > this.last || to < this.first) {
return [];
}
if (from == null) {
if (this.isInfiniteNegative) {
throw new Error("Tried to get all occurrences with no lower bound[" + this.toISOString() + "]");
}
from = this.first;
}
else if (from < this.first) {
from = this.first;
}
if (to == null) {
if (this.isInfinitePositive) {
throw new Error("Tried to get all occurrences with no upper bound[" + this.toISOString() + "]");
}
to = this.last;
}
else if (to > this.last) {
to = this.last;
}
var count = to - from + 1;
var initialDuration = this.durationBetween(from, to);
var currentOccurrence;
if (this.isInfiniteNegative) {
currentOccurrence = moment(this._end).subtract(initialDuration);
}
else {
currentOccurrence = moment(this._start).add(initialDuration);
}
var occurrences = [];
for (var i = 0; i < count; i++) {
occurrences.push(currentOccurrence);
currentOccurrence.add(this.duration);
}
return occurrences;
};
/**
* Get the recurrence (the index of the occurrence) after the supplied time
* @param after Moment or something that it parses (if a number, then in epoc ms)
*/
Interval.prototype.indexAfter = function (after) {
var afterMs = moment(after).valueOf();
var deltaMs;
if (this._start) {
deltaMs = afterMs - this._start;
}
else {
deltaMs = afterMs - this._end;
}
var durationMs = this.duration.asMilliseconds();
return Math.ceil(deltaMs / durationMs);
};
Interval.prototype.indexBefore = function (before) {
return this.indexAfter(before) - 1;
};
/**
* Get the occurrence happening after the supplied date.
* Throws Error if there is no occurrence after the supplied date
*/
Interval.prototype.occurrenceAfter = function (after) {
var afterMoment = moment(after);
var recurrence = this.indexAfter(afterMoment);
return this.occurrence(recurrence);
};
Interval.prototype.durationBetween = function (from, to) {
return moment.duration(this.duration.asMilliseconds() * (to - from));
};
Interval.extents = function (intervalList) {
var start = moment.min(intervalList.map(function (s) { return s.start; }));
var end = moment.max(intervalList.map(function (s) { return s.end; }));
return new Interval((start.isValid() ? start.toISOString() : '') + "/" + (end.isValid() ? end.toISOString() : ''));
};
Interval.prototype.toISOString = function () {
var parts = [];
if (this._recurs) {
parts.push("R" + (isFinite(this._repetitions) ? this._repetitions.toString() : ''));
}
if (this._start) {
parts.push(moment(this._start).toISOString());
if (this._infiniteSpan) {
parts.push('');
}
}
if (this._duration) {
parts.push(this._duration.toISOString());
}
if (this._end) {
parts.push(moment(this._end).toISOString());
if (this._infiniteSpan) {
parts.push('');
}
}
return parts.join('/');
};
Interval.prototype.toString = function () {
return this.toISOString();
};
return Interval;
}());
exports.Interval = Interval;
//# sourceMappingURL=interval.js.map