-
Notifications
You must be signed in to change notification settings - Fork 32
/
sherlock.js
788 lines (712 loc) · 27.9 KB
/
sherlock.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
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
/*!
* Sherlock
* Copyright (c) 2021 Neil Gupta
*/
var Sherlock = (function() {
var patterns = {
rangeSplitters: /(\bto\b|\-|\b(?:un)?till?\b|\bthrough\b|\bthru\b|\band\b|\bends?\b)/g,
// oct, october
months: "\\b(jan(?:uary)?|feb(?:ruary)?|mar(?:ch)?|apr(?:il)?|may|jun(?:e)?|jul(?:y)?|aug(?:ust)?|sep(?:tember)?|oct(?:ober)?|nov(?:ember)?|dec(?:ember)?)\\b",
// 3, 31, 31st, fifth
days: "\\b(?:(?:(?:on )?the )(?=\\d\\d?(?:st|nd|rd|th)))?([1-2]\\d|3[0-1]|0?[1-9])(?:st|nd|rd|th)?(?:,|\\b)",
// 2014, 1990
// Does not recognize 1930 for example because that could be confused with a valid time.
// Exceptions are made for years in 21st century.
years: "\\b(20\\d{2}|\\d{2}[6-9]\\d)\\b",
// 5/12/2014
shortForm: /\b(0?[1-9]|1[0-2])\/([1-2]\d|3[0-1]|0?[1-9])(?:\/(\d{2,4}))?\b/,
// 5-12-2014 (cannot be combined with above because we require year to use dashes)
shortFormD: /\b(0?[1-9]|1[0-2])\-([1-2]\d|3[0-1]|0?[1-9])\-(\d{2,4})\b/g,
// 2019/5/27, 2019-5-27
shortFormY: /\b(\d{4})[\/\-](0?[1-9]|1[0-2])[\/\-]([1-2]\d|3[0-1]|0?[1-9])\b/g,
// tue, tues, tuesday
weekdaysStr: "\\b(sun|mon|tue(?:s)?|wed(?:nes)?|thu(?:rs?)?|fri|sat(?:ur)?)(?:day)?\\b",
relativeDateStr: "((?:next|last|this) (?:week|month|year)|tom(?:orrow)?|tmrw|tod(?:ay)?|(?:right )?now|tonight|day after (?:tom(?:orrow)?|tmrw)|yest(?:erday)?|day before yest(?:erday)?)",
inRelativeDateStr: "(\\d{1,4}|a) (day|week|month|year)s? ?(ago|old)?",
inRelativeTime: /\b(\d{1,2} ?|a |an )(h(?:our|r)?|m(?:in(?:ute)?)?)s? ?(ago|old)?\b/,
inMilliTime: /\b(\d+) ?(s(?:ec(?:ond)?)?|ms|millisecond)s? ?(ago|old)?\b/,
midtime: /(?:@ ?)?\b(?:at )?(dawn|morn(?:ing)?|noon|afternoon|evening|night|midnight)\b/,
// 23:50, 0700, 1900
internationalTime: /\b(?:(0[0-9]|1[3-9]|2[0-3]):?([0-5]\d))\b/,
// 5, 12pm, 5:00, 5:00pm, at 5pm, @3a
explicitTime: /(?:@ ?)?\b(?:at |from )?(1[0-2]|[0-2]?[1-9])(?::?([0-5]\d))? ?([ap]\.?m?\.?)?(?:o'clock)?\b/,
more_than_comparator: /((?:more|greater|older|newer) than|after|before) \$(?:DATE|TIME)\$/i,
less_than_comparator: /((?:less|fewer) than) \$(?:DATE|TIME)\$/i,
// filler words must be preceded with a space to count
fillerWords: / (from|is|was|at|on|for|in|due(?! date)|(?:un)?till?)\b/,
// less aggressive filler words regex to use when rangeSplitters are disabled
fillerWords2: / (was|is|due(?! date))\b/
},
nowDate = null,
getNow = function() {
if (nowDate)
return new Date(nowDate.getTime());
else
return new Date();
},
readConfig = function(config_var) {
return (typeof Watson !== 'undefined' && Watson.config) ? Watson.config[config_var] : null;
},
parser = function(str, time, startTime) {
var ret = {},
dateMatch = false,
timeMatch = false,
strNummed = helpers.strToNum(str);
// parse date
if (dateMatch = matchDate(strNummed, time, startTime)) {
strNummed = strNummed.replace(new RegExp(dateMatch), '');
str = str.replace(new RegExp(helpers.numToStr(dateMatch)), '$DATE$');
}
// parse time
if (timeMatch = matchTime(strNummed, time, startTime))
str = str.replace(new RegExp(helpers.numToStr(timeMatch)), '$TIME$');
ret.eventTitle = str;
// if time data not given, then this is an all day event
ret.isAllDay = !!(dateMatch && !timeMatch && !dateMatch.match(/^(?:right )?now$|^tonight$/));
// check if date was parsed
ret.isValidDate = !!(dateMatch || timeMatch);
return ret;
},
matchTime = function(str, time, startTime) {
var match, matchConfidence = 0, matchedString = false, matchedHour, matchedMin, matchedHasMeridian;
if (match = str.match(new RegExp(patterns.explicitTime.source, "g"))) {
// if multiple matches found, pick the best one
match = match.sort(function (a, b) {
var aScore = a.trim().length,
bScore = b.trim().length;
// Weight matches that include full meridian
if (a.match(/(?:a|p).?m.?/))
aScore += 20;
if (b.match(/(?:a|p).?m.?/))
bScore += 20;
return bScore - aScore;
})[0].trim();
if (match.length <= 2 && str.trim().length > 2)
matchConfidence = 0;
else {
matchConfidence = match.length;
match = match.match(patterns.explicitTime);
var hour = parseInt(match[1])
, min = match[2] || 0
, meridian = match[3];
if (!meridian && match[1].startsWith('0') && str.match(patterns.internationalTime)) {
// match `02:00pm` with this matcher, but fallback to international time if just `02:00`
matchConfidence = 0;
} else if (meridian) {
// meridian is included, adjust hours accordingly
if (meridian.indexOf('p') === 0 && hour != 12)
hour += 12;
else if (meridian.indexOf('a') === 0 && hour == 12)
hour = 0;
matchConfidence += 20;
} else if (hour < 12 && (hour < 7 || hour <= time.getHours()))
// meridian is not included, adjust any ambiguous times
// if you type 3, it will default to 3pm
// if you type 11 at 5am, it will default to am,
// but if you type it at 2pm, it will default to pm
hour += 12;
matchedHour = hour;
matchedMin = min;
matchedHasMeridian = !!meridian;
matchedString = match[0];
}
}
var useLowConfidenceMatchedTime = function() {
if (matchedString) {
time.setHours(matchedHour, matchedMin, 0);
time.hasMeridian = matchedHasMeridian;
}
return matchedString;
};
if (matchConfidence < 4) {
if (match = str.match(patterns.inRelativeTime)) {
// if we matched 'a' or 'an', set the number to 1
if (isNaN(match[1]))
match[1] = 1;
if (match[3])
match[1] = parseInt(match[1])*-1;
switch(match[2].substring(0, 1)) {
case "h":
time.setHours(time.getHours() + parseInt(match[1]));
return match[0];
case "m":
time.setMinutes(time.getMinutes() + parseInt(match[1]));
return match[0];
default:
return useLowConfidenceMatchedTime();
}
} else if (match = str.match(patterns.inMilliTime)) {
if (match[3])
match[1] = parseInt(match[1])*-1;
switch(match[2].substring(0, 1)) {
case "s":
time.setSeconds(time.getSeconds() + parseInt(match[1]));
return match[0];
case "m":
time.setMilliseconds(time.getMilliseconds() + parseInt(match[1]));
return match[0];
default:
return useLowConfidenceMatchedTime();
}
} else if (match = str.match(patterns.midtime)) {
switch(match[1]) {
case "dawn":
time.setHours(5, 0, 0);
time.hasMeridian = true;
return match[0];
case "morn":
case "morning":
time.setHours(8, 0, 0);
time.hasMeridian = true;
return match[0];
case "noon":
time.setHours(12, 0, 0);
time.hasMeridian = true;
return match[0];
case "afternoon":
time.setHours(14, 0, 0);
time.hasMeridian = true;
return match[0];
case "evening":
time.setHours(19, 0, 0);
time.hasMeridian = true;
return match[0];
case "night":
time.setHours(21, 0, 0);
time.hasMeridian = true;
return match[0];
case "midnight":
time.setHours(0, 0, 0);
time.hasMeridian = true;
return match[0];
default:
return useLowConfidenceMatchedTime();
}
} else if (match = str.match(patterns.internationalTime)) {
time.setHours(match[1], match[2], 0);
time.hasMeridian = true;
return match[0];
} else
return useLowConfidenceMatchedTime();
} else
return useLowConfidenceMatchedTime();
},
matchDate = function(str, time, startTime) {
var match;
if (match = str.match(patterns.monthDay)) {
if (match[3]) {
time.setFullYear(match[3], helpers.changeMonth(match[1]), match[2]);
time.hasYear = true;
}
else
time.setMonth(helpers.changeMonth(match[1]), match[2]);
return match[0];
} else if (match = str.match(patterns.dayMonth)) {
if (match[3]) {
time.setFullYear(match[3], helpers.changeMonth(match[2]), match[1]);
time.hasYear = true;
}
else
time.setMonth(helpers.changeMonth(match[2]), match[1]);
return match[0];
} else if (match = str.match(patterns.shortForm)) {
var yearStr = match[3], year = null;
if (yearStr)
year = parseInt(yearStr);
if (year && yearStr.length < 4)
// if only 2 digits are given, assume years above 50 are in the 20th century, otherwise 21st century
year += year > 50 ? 1900 : 2000;
if (year) {
time.setFullYear(year, match[1] - 1, match[2]);
time.hasYear = true;
}
else
time.setMonth(match[1] - 1, match[2]);
return match[0];
} else if (match = str.match(patterns.oxtDays) || str.match(patterns.oxtDaysUK)) {
switch (match[1].substr(0, 3)) {
case "sun":
helpers.changeDay(time, 0, "oxt");
return match[0];
case "mon":
helpers.changeDay(time, 1, "oxt");
return match[0];
case "tue":
helpers.changeDay(time, 2, "oxt");
return match[0];
case "wed":
helpers.changeDay(time, 3, "oxt");
return match[0];
case "thu":
helpers.changeDay(time, 4, "oxt");
return match[0];
case "fri":
helpers.changeDay(time, 5, "oxt");
return match[0];
case "sat":
helpers.changeDay(time, 6, "oxt");
return match[0];
default:
return false;
}
} else if (match = str.match(patterns.weekdays)) {
switch (match[2].substr(0, 3)) {
case "sun":
helpers.changeDay(time, 0, match[1]);
return match[0];
case "mon":
helpers.changeDay(time, 1, match[1]);
return match[0];
case "tue":
helpers.changeDay(time, 2, match[1]);
return match[0];
case "wed":
helpers.changeDay(time, 3, match[1]);
return match[0];
case "thu":
helpers.changeDay(time, 4, match[1]);
return match[0];
case "fri":
helpers.changeDay(time, 5, match[1]);
return match[0];
case "sat":
helpers.changeDay(time, 6, match[1]);
return match[0];
default:
return false;
}
} else if (match = str.match(patterns.inRelativeDateFromRelativeDate)) {
if (helpers.relativeDateMatcher(match[4], time) && helpers.inRelativeDateMatcher(match[1], match[2], match[3], time))
return match[0];
else
return false;
} else if (match = str.match(patterns.relativeDate)) {
if (helpers.relativeDateMatcher(match[1], time))
return match[0];
else
return false;
} else if (match = str.match(patterns.inRelativeDate)) {
if (helpers.inRelativeDateMatcher(match[1], match[2], match[3], time))
return match[0];
else
return false;
} else if (match = str.match(new RegExp(patterns.days, "g"))) {
// if multiple matches found, pick the best one
match = match.sort(function (a, b) { return b.trim().length - a.trim().length; })[0].trim();
// check if the possible date match meets our reasonable assumptions...
// if the match doesn't start with 'on',
if ((match.indexOf('on') !== 0 &&
// and if the match doesn't start with 'the' and end with a comma,
!(match.indexOf('the') === 0 && match.indexOf(',', match.length - 1) !== -1) &&
// and if the match isn't at the end of the overall input, then drop it.
str.indexOf(match, str.length - match.length - 1) === -1) ||
// But if one of those is true, make sure it passes these other checks too...
// if this is an end date and the start date isn't an all day value,
(!(startTime && startTime.isAllDay) &&
// and if this match is too short to mean something,
match.length <= 2))
// then drop it.
return false;
match = match.match(patterns.daysOnly);
var month = time.getMonth(),
day = match[1];
// if this date is in the past, move it to next month
if (day < time.getDate())
month++;
time.setMonth(month, day);
return match[0];
} else
return false;
},
// Make some intelligent assumptions of what was meant, even when given incomplete information
makeAdjustments = function(start, end, isAllDay, str, ret) {
var now = getNow();
if (end) {
if (start > end && end > now && helpers.isSameDay(start, end) && helpers.isSameDay(start, now)) {
if (start.hasMeridian)
// we explicitly set the meridian, so don't mess with the hours
start.setDate(start.getDate() - 1);
else {
// we are dealing with a time range that is today with start > end
// (ie. 9pm - 5pm when we want 9am - 5pm), roll back 12 hours.
start.setHours(start.getHours() - 12);
// if start is still higher than end, that means we probably have
// 9am - 5am, so roll back another 12 hours to get 9pm yesterday - 5am today
if (start > end)
start.setHours(start.getHours() - 12);
}
}
else if (start > end && end < now && helpers.monthDiff(end, start) >= 3 && !end.hasYear) {
end.setFullYear(end.getFullYear() + 1);
}
else if (start > end && helpers.isSameDay(start, end)) {
end.setDate(start.getDate() + 1);
}
else if (end < now && str.indexOf(" was ") === -1 && helpers.monthDiff(end, now) >= 3 && !end.hasYear && !start.hasYear) {
end.setFullYear(end.getFullYear() + 1);
start.setFullYear(start.getFullYear() + 1);
}
} else if (start) {
if (start <= now && !start.hasYear && !str.match(/was|ago|old\b/)) {
if (helpers.isSameDay(start, now) && !isAllDay) {
if (start.hasMeridian || start.getHours() < 19)
// either we explicitly set the meridian or the time
// is less than 7pm, so don't mess with the hours
start.setDate(start.getDate() + 1);
else {
start.setHours(start.getHours() + 12);
// if start is still older than now, roll forward a day instead
if (start <= now) {
start.setHours(start.getHours() - 12);
start.setDate(start.getDate() + 1);
}
}
} else if (helpers.monthDiff(start, now) >= 3)
start.setFullYear(start.getFullYear() + 1);
}
// check for open ranges (more than...)
if (ret.eventTitle.match(patterns.more_than_comparator)) {
if ((start <= now && (!helpers.isSameDay(start, now) || str.match(/ago|old\b/)) &&
!ret.eventTitle.match(/after|newer/i)) ||
ret.eventTitle.match(/older|before/i)) {
ret.endDate = new Date(start.getTime());
ret.startDate = new Date(1900, 0, 1, 0, 0, 0, 0);
} else {
ret.endDate = new Date(3000, 0, 1, 0, 0, 0, 0);
}
ret.eventTitle = ret.eventTitle.replace(patterns.more_than_comparator, '');
}
// check for closed ranges (less than...)
else if (ret.eventTitle.match(patterns.less_than_comparator)) {
if (start <= now) {
if (helpers.isSameDay(start, now) && !str.match(/ago|old\b/)) {
// make an exception for "less than today" or "less than now"
ret.endDate = new Date(start.getTime());
ret.startDate = new Date(1900, 0, 1, 0, 0, 0, 0);
} else
ret.endDate = new Date(now.getTime());
} else {
ret.endDate = new Date(start.getTime());
ret.startDate = new Date(now.getTime());
}
ret.eventTitle = ret.eventTitle.replace(patterns.less_than_comparator, '');
}
}
},
helpers = {
relativeDateMatcher: function(match, time) {
var now = getNow();
switch(match) {
case "next week":
time.setFullYear(now.getFullYear(), now.getMonth(), now.getDate() + 7);
time.hasYear = true;
return true;
case "next month":
time.setFullYear(now.getFullYear(), now.getMonth() + 1, now.getDate());
time.hasYear = true;
return true;
case "next year":
time.setFullYear(now.getFullYear() + 1, now.getMonth(), now.getDate());
time.hasYear = true;
return true;
case "last week":
time.setFullYear(now.getFullYear(), now.getMonth(), now.getDate() - 7);
time.hasYear = true;
return true;
case "last month":
time.setFullYear(now.getFullYear(), now.getMonth() - 1, now.getDate());
time.hasYear = true;
return true;
case "last year":
time.setFullYear(now.getFullYear() - 1, now.getMonth(), now.getDate());
time.hasYear = true;
return true;
case "tom":
case "tmrw":
case "tomorrow":
time.setFullYear(now.getFullYear(), now.getMonth(), now.getDate() + 1);
time.hasYear = true;
return true;
case "day after tom":
case "day after tmrw":
case "day after tomorrow":
time.setFullYear(now.getFullYear(), now.getMonth(), now.getDate() + 2);
time.hasYear = true;
return true;
case "this week":
case "this month":
case "this year": // this week|month|year is pretty meaningless, but let's include it so that it parses as today
case "tod":
case "today":
time.setFullYear(now.getFullYear(), now.getMonth(), now.getDate());
time.hasYear = true;
return true;
case "now":
case "right now":
case "tonight":
time.setFullYear(now.getFullYear(), now.getMonth(), now.getDate());
time.setHours(now.getHours(), now.getMinutes(), now.getSeconds(), 0);
if (match === "tonight" && time.getHours() < 21)
time.setHours(21, 0, 0, 0); // Assume "tonight" starts at 9pm
time.hasMeridian = true;
time.hasYear = true;
return true;
case "yest":
case "yesterday":
time.setFullYear(now.getFullYear(), now.getMonth(), now.getDate() - 1);
time.hasYear = true;
return true;
case "day before yest":
case "day before yesterday":
time.setFullYear(now.getFullYear(), now.getMonth(), now.getDate() - 2);
time.hasYear = true;
return true;
default:
return false;
}
},
inRelativeDateMatcher: function(num, scale, ago, time) {
// if we matched 'a' or 'an', set the number to 1
if (isNaN(num))
num = 1;
else
num = parseInt(num);
if (ago)
num = num*-1;
switch(scale) {
case "day":
time.setDate(time.getDate() + num);
time.hasYear = true;
return true;
case "week":
time.setDate(time.getDate() + num*7);
time.hasYear = true;
return true;
case "month":
time.setMonth(time.getMonth() + num);
time.hasYear = true;
return true;
case "year":
time.setFullYear(time.getFullYear() + num);
time.hasYear = true;
return true;
default:
return false;
}
},
// convert month string to number
changeMonth: function(month) {
return this.monthToInt[month.substr(0, 3)];
},
// find the nearest future date that is on the given weekday
changeDay: function(time, newDay, hasNext) {
var diff = 7 - time.getDay() + newDay;
if ((diff > 7 && hasNext === undefined) || hasNext === "last")
diff -= 7;
if (diff >= 0 && hasNext === "last")
// If entering "last saturday" on a Saturday, for example,
// diff will be 0 when it should be -7
diff -= 7;
if (hasNext === "oxt")
diff += 7;
time.setDate(time.getDate() + diff);
},
monthDiff: function(d1, d2) {
var months;
months = (d2.getFullYear() - d1.getFullYear()) * 12;
months -= d1.getMonth() + 1;
months += d2.getMonth() + 1;
return months <= 0 ? 0 : months;
},
escapeRegExp: function(str) {
return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
},
isSameDay: function(date1, date2) {
return date1.getMonth() === date2.getMonth() && date1.getDate() === date2.getDate() && date1.getFullYear() === date2.getFullYear();
},
monthToInt: {"jan": 0, "feb": 1, "mar": 2, "apr": 3, "may": 4, "jun": 5, "jul": 6, "aug": 7, "sep": 8, "oct": 9, "nov": 10, "dec": 11},
// mapping of words to numbers
wordsToInt: {
'one' : 1,
'first' : 1,
'two' : 2,
'second' : 2,
'three' : 3,
'third' : 3,
'four' : 4,
'fourth' : 4,
'five' : 5,
'fifth' : 5,
'six' : 6,
'sixth' : 6,
'seven' : 7,
'seventh' : 7,
'eight' : 8,
'eighth' : 8,
'nine' : 9,
'ninth' : 9,
'ten' : 10,
'tenth' : 10
},
// mapping of number to words
intToWords: [
'one|first',
'two|second',
'three|third',
'four|fourth',
'five|fifth',
'six|sixth',
'seven|seventh',
'eight|eighth',
'nine|ninth',
'ten|tenth'
],
// converts all the words in a string into numbers, such as four -> 4
strToNum: function(str) {
return str.replace(patterns.digit, function(val) {
var out = helpers.wordsToInt[val];
if (val.indexOf('th', val.length - 2) !== -1)
out += 'th';
else if (val.indexOf('st', val.length - 2) !== -1)
out += 'st';
else if (val.indexOf('nd', val.length - 2) !== -1)
out += 'nd';
else if (val.indexOf('rd', val.length - 2) !== -1)
out += 'rd';
return out;
});
},
// converts all the numbers in a string into regex for number|word, such as 4 -> 4|four
numToStr: function(str) {
return str.replace(/((?:[1-9]|10)(?:st|nd|rd|th)?)/g, function(val) {
return '(?:' + val + '|' + helpers.intToWords[parseInt(val) - 1] + ')';
});
}
};
// may 5, may 5th
patterns.monthDay = new RegExp(patterns.months + " " + patterns.days + "(?: " + patterns.years + ")?");
// 5th may, 5 may
patterns.dayMonth = new RegExp(patterns.days + "(?: (?:day )?of)? " + patterns.months + "(?: " + patterns.years + ")?");
// 5, 5th
patterns.daysOnly = new RegExp(patterns.days);
patterns.digit = new RegExp("\\b(" + helpers.intToWords.join("|") + ")\\b", "g");
// today, tomorrow, day after tomorrow
patterns.relativeDate = new RegExp("\\b" + patterns.relativeDateStr + "\\b");
// in 2 weeks
patterns.inRelativeDate = new RegExp("\\b" + patterns.inRelativeDateStr + "\\b");
// 2 weeks from tomorrow
patterns.inRelativeDateFromRelativeDate = new RegExp("\\b" + patterns.inRelativeDateStr + " from " + patterns.relativeDateStr + "\\b");
// next Friday, thu
patterns.weekdays = new RegExp("(?:(next|last) (?:week (?:on )?)?)?" + patterns.weekdaysStr);
// oxt monday
patterns.oxtDays = new RegExp("(?:\\boxt|\\bweek next) " + patterns.weekdaysStr);
// thursday week
patterns.oxtDaysUK = new RegExp(patterns.weekdaysStr + " week\\b");
if(!String.prototype.trim) {
String.prototype.trim = function () {
return this.replace(/^\s+|\s+$/g,'');
};
}
return {
// parses a string and returns an object defining the basic event
// with properties: eventTitle, startDate, endDate, isAllDay
// plus anything Watson adds on...
parse: function(str) {
// check for null input
if (str === null) str = '';
var date = getNow(),
// Check if Watson is around. If not, pretend like he is to keep Sherlock company.
result = (typeof Watson !== 'undefined') ? Watson.preprocess(str) : [str, {}],
str = result[0],
ret = result[1];
str = str.replace(patterns.shortFormD, '$1/$2/$3');
str = str.replace(patterns.shortFormY, '$2/$3/$1');
// token the string to start and stop times
var tokens = readConfig("disableRanges") ? [str.toLowerCase()] : str.toLowerCase().split(patterns.rangeSplitters);
patterns.rangeSplitters.lastIndex = 0;
// normalize all dates to 0 milliseconds
date.setMilliseconds(0);
while (!ret.startDate) {
// parse the start date
if ((result = parser(tokens[0], date, null)) !== null) {
if (result.isAllDay)
// set to midnight
date.setHours(0, 0, 0);
ret.isAllDay = result.isAllDay;
ret.eventTitle = result.eventTitle;
ret.startDate = result.isValidDate ? date : null;
}
// if no time
if (!ret.startDate && tokens.length >= 3) {
// join the next 2 tokens to the current one
var tokensTmp = [tokens[0] + tokens[1] + tokens[2]];
for (var k = 3; k < tokens.length; k++) {
tokensTmp.push(tokens[k]);
}
tokens = tokensTmp;
} else
break;
}
// parse the 2nd half of the date range, if it exists
while (!ret.endDate) {
if (tokens.length > 1) {
date = new Date(date.getTime());
// parse the end date
if ((result = parser(tokens[2], date, ret)) !== null) {
if (ret.isAllDay)
// set to midnight
date.setHours(0, 0, 0);
if (result.eventTitle.replace(/\$(?:DATE|TIME)\$/g, '').length > ret.eventTitle.replace(/\$(?:DATE|TIME)\$/g, '').length)
ret.eventTitle = result.eventTitle;
ret.endDate = result.isValidDate ? date : null;
}
}
if (!ret.endDate) {
if (tokens.length >= 4) {
// join the next 2 tokens to the current one
var tokensTmp = [tokens[0], tokens[1], tokens[2] + tokens[3] + tokens[4]];
for (var k = 5; k < tokens.length; k++) {
tokensTmp.push(tokens[k]);
}
tokens = tokensTmp;
} else {
ret.endDate = null;
break;
}
}
}
makeAdjustments(ret.startDate, ret.endDate, ret.isAllDay, str, ret);
// get capitalized version of title
if (ret.eventTitle) {
ret.eventTitle = ret.eventTitle.replace(/\$(?:DATE|TIME)\$/g, '');
var fillerWords = readConfig("disableRanges") ? patterns.fillerWords2 : patterns.fillerWords;
ret.eventTitle = ret.eventTitle.split(fillerWords)[0].trim();
ret.eventTitle = ret.eventTitle.replace(/(?:^| )(?:\.|-$|by$|in$|at$|from$|on$|starts?$|for$|(?:un)?till?$|!|,|;)+/g, '').replace(/ +/g, ' ').trim();
var match = str.match(new RegExp(helpers.escapeRegExp(ret.eventTitle), "i"));
if (match) {
ret.eventTitle = match[0].replace(/ +/g, ' ').trim(); // replace multiple spaces
if (ret.eventTitle == '')
ret.eventTitle = null;
}
} else
ret.eventTitle = null;
if (typeof Watson !== 'undefined')
Watson.postprocess(ret);
return ret;
},
// Sets what time Sherlock thinks it is right now, regardless of the actual system time.
// Useful for debugging different times. Pass a Date object to set 'now' to a time of your choosing.
// Don't pass in anything to reset 'now' to the real time.
_setNow: function(newDate) {
nowDate = newDate;
}
};
})();
// Add AMD compatibility.
if (typeof define === 'function' && define.amd) {
define(Sherlock);
}
// Add CommonJS compatibility.
else if (typeof module !== 'undefined' && module.exports) {
module.exports = Sherlock;
}