/
Pattern.ts
459 lines (413 loc) · 12.2 KB
/
Pattern.ts
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 { Functions as fn } from './Functions';
import { Day, DayProperty } from './Day';
import { Suffix } from './Suffix';
import { Weekday } from './Weekday';
import { FrequencyValueEvery, FrequencyValue } from './Frequency';
import { Schedule, ScheduleInput } from './Schedule';
/**
* Describes a [[Pattern]] given a [[Day]] to base it on.
*
* @param day The day to base the description on.
* @returns The description of the pattern.
*/
export type DescribePattern = (day: Day) => string;
/**
* A rule helps parse [[ScheduleInput]] and determines whether it matches the
* given pattern.
*
* - When a number is given, the input MUST be an array of the same length and contain any values.
* - When an array of numbers is given, the input MUST be an array containing the same values.
* - When a TRUE is given the input MUST contain that property and can be any value.
* - When a FALSE is given the input MAY contain that property (optional).
* - When a property is NOT specified, the input MUST NOT contain that property.
* - When an object with every is given, the input must match the every and offset values (have the same frequency).
*/
export type PatternRule =
number | // has array with this number of elements
number[] | // is array with same values
boolean | // is true or false
FrequencyValueEvery; // is object with matching every and offset
/**
* The set of rules you can specify for determining if a [[ScheduleInput]]
* matches a pattern.
*/
export interface PatternRules
{
dayOfWeek?: PatternRule;
dayOfMonth?: PatternRule;
lastDayOfMonth?: PatternRule;
dayOfYear?: PatternRule;
month?: PatternRule;
week?: PatternRule;
year?: PatternRule;
weekOfYear?: PatternRule;
weekspanOfYear?: PatternRule;
fullWeekOfYear?: PatternRule;
lastWeekspanOfYear?: PatternRule;
lastFullWeekOfYear?: PatternRule;
weekOfMonth?: PatternRule;
weekspanOfMonth?: PatternRule;
fullWeekOfMonth?: PatternRule;
lastWeekspanOfMonth?: PatternRule;
lastFullWeekOfMonth?: PatternRule;
}
/**
* A class which helps describe [[ScheduleInput]] if it matches a pattern.
*/
export class Pattern
{
/**
* The properties in the [[ScheduleInput]] which are compared against the
* rules of a pattern.
*/
public static PROPS: DayProperty[] =
[
'dayOfWeek', 'dayOfMonth', 'lastDayOfMonth', 'dayOfYear',
'month', 'week', 'year',
'weekOfYear', 'weekspanOfYear', 'fullWeekOfYear', 'lastWeekspanOfYear', 'lastFullWeekOfYear',
'weekOfMonth', 'weekspanOfMonth', 'fullWeekOfMonth', 'lastWeekspanOfMonth', 'lastFullWeekOfMonth'
];
/**
* Whether this pattern should be "listed" or not. Visual schedulers may
* provide a shortcut to describing and changing a [[Schedule]] through
* patterns and any pattern where listed is `true` could be an option in a
* list. The default patterns are all listed.
*/
public listed: boolean;
/**
* The function which describes this pattern given a [[Day]] to base it on.
*/
public describe: DescribePattern;
/**
* The name of this pattern. This is not typically displayed to a user, just
* to uniquely identify a pattern.
*/
public name: string;
/**
* The rules for matching a pattern to a [[Schedule]] or applying a pattern to
* a schedule.
*/
public rules: PatternRules;
/**
* Creates a new pattern.
*
* @param name The unique name of the pattern.
* @param listed If the pattern is "listed" [[Pattern.listed]].
* @param describe A function to describe the pattern given a [[Day]].
* @param rules The rules which describe how to detect and apply the pattern
* to schedule input.
*/
public constructor(name: string, listed: boolean, describe: DescribePattern, rules: PatternRules)
{
this.name = name;
this.listed = listed;
this.describe = describe;
this.rules = rules;
}
/**
* Applies this pattern to a [[Schedule]] or [[ScheduleInput]] removing and
* adding any necessary properties from the input to match this pattern -
* based around the day provided.
*
* @param schedule The schedule to update to match this pattern.
* @param day The day to base the schedule on.
* @returns The reference to the input passed in.
*/
public apply<M, I extends ScheduleInput<M> | Schedule<M>>(schedule: I, day: Day): I
{
if (schedule instanceof Schedule)
{
this.applyGeneric(day,
(prop, frequency) => schedule.setFrequency( prop, frequency ),
(prop) => schedule.setFrequency( prop )
);
schedule.updateChecks();
}
else
{
this.applyGeneric(day,
(prop, frequency) => schedule[ prop ] = frequency,
(prop) => delete schedule[ prop ]
);
}
return schedule;
}
/**
* Applies this pattern to any object provided they implement the
* `setFrequency` and `removeFrequency` functions.
*
* @param day The day to base the schedule on.
* @param setFrequency The function which sets the frequency on the object.
* @param removeFrequency The function to remove a frequency from the object.
*/
public applyGeneric(day: Day,
setFrequency: (property: DayProperty, frequency: any) => any,
removeFrequency: (property: DayProperty) => any): void
{
for (let prop of Pattern.PROPS)
{
let rule = this.rules[ prop ];
// Should have one value
if (rule === 1)
{
setFrequency( prop, [day[ prop ]] );
}
// Can be any of the values in the array
if (fn.isArray(rule))
{
setFrequency( prop, rule );
}
// Must not be present
if (!fn.isDefined(rule))
{
removeFrequency( prop );
}
}
}
/**
* Determines whether the given [[Schedule]] or [[ScheduleInput]] matches this
* pattern. Optionally a day can be provided to make sure the day matches the
* schedule and pattern together.
*
* @param schedule The schedule input to test.
* @param exactlyWith A day to further validate against for matching.
* @returns `true` if the schedule was a match to this pattern with the
* day if one was provided, otherwise `false`.
*/
public isMatch<M, I extends ScheduleInput<M> | Schedule<M>>(schedule: I, exactlyWith?: Day): boolean
{
if (schedule instanceof Schedule)
{
return this.isMatchGeneric((prop) => schedule[ prop ].input, exactlyWith);
}
else
{
return this.isMatchGeneric((prop) => schedule[ prop ], exactlyWith);
}
}
/**
* Determines whether the given input matches this pattern. Optionally a day
* can be provided to make sure the day matches the schedule and pattern
* together.
*
* @param input The schedule input to test.
* @param exactlyWith A day to further validate against for matching.
* @returns `true` if the schedule input was a match to this pattern with the
* day if one was provided, otherwise `false`.
*/
public isMatchGeneric(getFrequency: (property: DayProperty) => FrequencyValue, exactlyWith?: Day): boolean
{
let exactly: boolean = fn.isDefined( exactlyWith );
for (let prop of Pattern.PROPS)
{
let rule = this.rules[ prop ];
let curr = getFrequency( prop );
// Optional, skip it
if (rule === false)
{
continue;
}
// Requires any value
if (rule === true && !curr)
{
return false;
}
// Must not be present
if (!fn.isDefined(rule) && curr)
{
return false;
}
// Must be an array of the same size
if (fn.isNumber(rule))
{
if (fn.isArray(curr) && (<number[]>curr).length === rule)
{
if (exactly && (<number[]>curr).indexOf( <number>exactlyWith[ prop ] ) === -1)
{
return false;
}
}
else
{
return false;
}
}
// Must be an array of the same values
if (fn.isArray(rule))
{
if (!fn.isArray(curr))
{
return false;
}
if (rule.length !== (<number[]>curr).length)
{
return false;
}
for (var i = 0; i < rule.length; i++)
{
if (rule[ i ] !== curr[ i ])
{
return false;
}
}
if (exactly && rule.indexOf( exactlyWith[ prop ] ) === -1)
{
return false;
}
}
// Must be an object with same over & offset.
if (fn.isObject(rule))
{
if (!fn.isObject(curr))
{
return false;
}
var ruleOffset = rule.offset || 0;
var currOffset = (<FrequencyValueEvery>curr).offset || 0;
if (currOffset !== ruleOffset || curr.every !== rule.every)
{
return false;
}
if (exactly && (<number>exactlyWith[ prop ] % rule.every) !== ruleOffset)
{
return false;
}
}
}
return true;
}
/**
* Returns the pattern with the given name if one exists. If you add your own
* patterns make sure to add them to [[PatternMap]].
*
* @param name The name of the pattern to return.
* @return The instance to the pattern with the same name.
*/
public static withName(name: string): Pattern
{
return PatternMap[ name ];
}
/**
* Finds a matching pattern to the given input searching through [[Patterns]]
* for matches. Optionally it will only look at patterns where listed = `true`.
*
* @param input The schedule input to use.
* @param listedOnly When `true` only patterns with [[Pattern.listed]] set to
* `true` will be looked at, otherwise all patterns are looked at.
* @param exactlyWith A day to further validate against for matching.
* @see [[Pattern.isMatch]]
*/
public static findMatch<M, I extends ScheduleInput<M> | Schedule<M>>(input: I, listedOnly: boolean = true, exactlyWith?: Day): Pattern
{
for (let pattern of Patterns)
{
if ((pattern.listed || !listedOnly) && pattern.isMatch<M, I>( input, exactlyWith ))
{
return pattern;
}
}
return null;
}
}
/**
* The list of patterns that can be searched through for matches to schedule
* input.
*
* @see [[Pattern.findMatch]]
*/
export let Patterns: Pattern[] = [
new Pattern(
'none', true,
(day: Day) => 'Does not repeat',
{
year: 1,
month: 1,
dayOfMonth: 1
}
),
new Pattern(
'daily', true,
(day: Day) => 'Daily',
{
}
),
new Pattern(
'weekly', true,
(day: Day) => 'Weekly on ' + day.format('dddd'),
{
dayOfWeek: 1
}
),
new Pattern(
'monthlyWeek', true,
(day: Day) => 'Monthly on the ' + Suffix.CACHE[day.weekspanOfMonth + 1] + ' ' + day.format('dddd'),
{
dayOfWeek: 1,
weekspanOfMonth: 1
}
),
new Pattern(
'annually', true,
(day: Day) => 'Annually on ' + day.format('MMMM Do'),
{
month: 1,
dayOfMonth: 1
}
),
new Pattern(
'annuallyMonthWeek', true,
(day: Day) => 'Annually on the ' + Suffix.CACHE[day.weekspanOfMonth + 1] + ' ' + day.format('dddd') + ' of ' + day.format('MMMM'),
{
month: 1,
dayOfWeek: 1,
weekspanOfMonth: 1
}
),
new Pattern(
'weekday', true,
(day: Day) => 'Every weekday (Monday to Friday)',
{
dayOfWeek: [Weekday.MONDAY, Weekday.TUESDAY, Weekday.WEDNESDAY, Weekday.THURSDAY, Weekday.FRIDAY]
}
),
new Pattern(
'monthly', true,
(day: Day) => 'Monthly on the ' + day.format('Do') + ' day',
{
dayOfMonth: 1
}
),
new Pattern(
'custom', true,
(day: Day) => 'Custom...',
{
dayOfWeek: false,
dayOfMonth: false,
lastDayOfMonth: false,
dayOfYear: false,
year: false,
month: false,
week: false,
weekOfYear: false,
weekspanOfYear: false,
fullWeekOfYear: false,
lastWeekspanOfYear: false,
lastFullWeekOfYear: false,
weekOfMonth: false,
weekspanOfMonth: false,
fullWeekOfMonth: false,
lastWeekspanOfMonth: false,
lastFullWeekOfMonth: false
}
)
];
/**
* The map of patterns keyed by their name.
*
* @see [[Pattern.withName]]
*/
export let PatternMap: { [name: string]: Pattern } = {};
for (let pattern of Patterns)
{
PatternMap[ pattern.name ] = pattern;
}