forked from jkbrzt/rrule
-
Notifications
You must be signed in to change notification settings - Fork 0
/
rrule.js
1822 lines (1605 loc) · 56.6 KB
/
rrule.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
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*!
* rrule.js - Library for working with recurrence rules for calendar dates.
* v1.0.0-beta
* https://github.com/jkbr/rrule
*
* Copyright 2010, Jakub Roztocil and Lars Schoning
* Licenced under the BSD licence.
* https://github.com/jkbr/rrule/blob/master/LICENCE
*
* Based on:
* python-dateutil - Extensions to the standard Python datetime module.
* Copyright (c) 2003-2011 - Gustavo Niemeyer <[email protected]>
* Copyright (c) 2012 - Tomi Pieviläinen <[email protected]>
* https://github.com/jkbr/rrule/blob/master/LICENCE
*
*/
(function(root){
var serverSide = typeof module !== 'undefined' && module.exports;
var _;
if (serverSide) {
_ = require('underscore');
} else if (!(_ = root._)) {
throw 'You need to include underscore.js for rrule to work.'
}
var getnlp = function() {
if (!getnlp._nlp) {
if (serverSide) {
// Lazy, runtime import to avoid circular refs.
getnlp._nlp = require('./nlp')
} else if (!(getnlp._nlp = root._RRuleNLP)) {
throw 'You need to include rrule/nlp.js ' +
'for fromText/toText to work.'
}
}
return getnlp._nlp;
}
//=============================================================================
// Date utilities
//=============================================================================
/**
* General date-related utilities.
* Also handles several incompatibilities between JavaScript and Python
*
*/
var dateutil = {
MONTH_DAYS: [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31],
/**
* Number of milliseconds of one day
*/
ONE_DAY: 1000 * 60 * 60 * 24,
/**
* @see: <http://docs.python.org/library/datetime.html#datetime.MAXYEAR>
*/
MAXYEAR: 9999,
/**
* Python uses 1-Jan-1 as the base for calculating ordinals but we don't
* want to confuse the JS engine with milliseconds > Number.MAX_NUMBER,
* therefore we use 1-Jan-1970 instead
*/
ORDINAL_BASE: new Date(1970, 0, 1),
/**
* Python: MO-SU: 0 - 6
* JS: SU-SAT 0 - 6
*/
PY_WEEKDAYS: [6, 0, 1, 2, 3, 4, 5],
/**
* py_date.timetuple()[7]
*/
getYearDay: function(date) {
var dateNoTime = new Date(
date.getFullYear(), date.getMonth(), date.getDate());
return Math.ceil(
(dateNoTime - new Date(date.getFullYear(), 0, 1))
/ dateutil.ONE_DAY) + 1;
},
isLeapYear: function(year) {
if (year instanceof Date) {
year = year.getFullYear();
}
return ((year % 4 === 0) && (year % 100 !== 0)) || (year % 400 === 0);
},
/**
* @return {Number} the date's timezone offset in ms
*/
tzOffset: function(date) {
return date.getTimezoneOffset() * 60 * 1000
},
/**
* @see: <http://www.mcfedries.com/JavaScript/DaysBetween.asp>
*/
daysBetween: function(date1, date2) {
// The number of milliseconds in one day
// Convert both dates to milliseconds
var date1_ms = date1.getTime() - dateutil.tzOffset(date1);
var date2_ms = date2.getTime() - dateutil.tzOffset(date2);
// Calculate the difference in milliseconds
var difference_ms = Math.abs(date1_ms - date2_ms);
// Convert back to days and return
return Math.round(difference_ms / dateutil.ONE_DAY);
},
/**
* @see: <http://docs.python.org/library/datetime.html#datetime.date.toordinal>
*/
toOrdinal: function(date) {
return dateutil.daysBetween(date, dateutil.ORDINAL_BASE);
},
/**
* @see - <http://docs.python.org/library/datetime.html#datetime.date.fromordinal>
*/
fromOrdinal: function(ordinal) {
var millisecsFromBase = ordinal * dateutil.ONE_DAY;
return new Date(dateutil.ORDINAL_BASE.getTime()
- dateutil.tzOffset(dateutil.ORDINAL_BASE)
+ millisecsFromBase);
},
/**
* @see: <http://docs.python.org/library/calendar.html#calendar.monthrange>
*/
monthRange: function(year, month) {
var date = new Date(year, month, 1);
return [dateutil.getWeekday(date), dateutil.getMonthDays(date)];
},
getMonthDays: function(date) {
var month = date.getMonth();
return month == 1 && dateutil.isLeapYear(date)
? 29 : dateutil.MONTH_DAYS[month];
},
/**
* @return {Number} python-like weekday
*/
getWeekday: function(date) {
return dateutil.PY_WEEKDAYS[date.getDay()];
},
/**
* @see: <http://docs.python.org/library/datetime.html#datetime.datetime.combine>
*/
combine: function(date, time) {
time = time || date;
return new Date(
date.getFullYear(), date.getMonth(), date.getDate(),
time.getHours(), time.getMinutes(), time.getSeconds()
);
},
clone: function(date) {
var dolly = new Date(date.getTime());
dolly.setMilliseconds(0);
return dolly;
},
cloneDates: function(dates) {
var clones = [];
for (var i = 0; i < dates.length; i++) {
clones.push(dateutil.clone(dates[i]));
}
return clones;
},
/**
* Sorts an array of Date or dateutil.Time objects
*/
sort: function(dates) {
dates.sort(function(a, b){
return a.getTime() - b.getTime();
});
},
timeToUntilString: function(time) {
var date = new Date(time);
var comp, comps = [
date.getUTCFullYear(),
date.getUTCMonth() + 1,
date.getUTCDate(),
'T',
date.getUTCHours(),
date.getUTCMinutes(),
date.getUTCSeconds(),
'Z'
];
for (var i = 0; i < comps.length; i++) {
comp = comps[i];
if (!/[TZ]/.test(comp) && comp < 10) {
comps[i] = '0' + String(comp);
}
}
return comps.join('');
}
};
dateutil.Time = function(hour, minute, second) {
this.hour = hour;
this.minute = minute;
this.second = second;
};
dateutil.Time.prototype = {
getHours: function() {
return this.hour;
},
getMinutes: function() {
return this.minute;
},
getSeconds: function() {
return this.second;
},
getTime: function() {
return ((this.hour * 60 * 60)
+ (this.minute * 60)
+ this.second)
* 1000;
}
};
//=============================================================================
// Helper functions
//=============================================================================
/**
* Simplified version of python's range()
*/
var range = function(start, end) {
if (arguments.length === 1) {
end = start;
start = 0;
}
var rang = [];
for (var i = start; i < end; i++) {
rang.push(i);
}
return rang;
};
var repeat = function(value, times) {
var i = 0, array = [];
if (value instanceof Array) {
for (; i < times; i++) {
array[i] = [].concat(value);
}
} else {
for (; i < times; i++) {
array[i] = value;
}
}
return array;
};
/**
* closure/goog/math/math.js:modulo
* Copyright 2006 The Closure Library Authors.
* The % operator in JavaScript returns the remainder of a / b, but differs from
* some other languages in that the result will have the same sign as the
* dividend. For example, -1 % 8 == -1, whereas in some other languages
* (such as Python) the result would be 7. This function emulates the more
* correct modulo behavior, which is useful for certain applications such as
* calculating an offset index in a circular list.
*
* @param {number} a The dividend.
* @param {number} b The divisor.
* @return {number} a % b where the result is between 0 and b (either 0 <= x < b
* or b < x <= 0, depending on the sign of b).
*/
var pymod = function(a, b) {
var r = a % b;
// If r and b differ in sign, add b to wrap the result to the correct sign.
return (r * b < 0) ? r + b : r;
};
/**
* @see: <http://docs.python.org/library/functions.html#divmod>
*/
var divmod = function(a, b) {
return {div: Math.floor(a / b), mod: pymod(a, b)};
};
/**
* Python-like boolean
* @return {Boolean} value of an object/primitive, taking into account
* the fact that in Python an empty list's/tuple's
* boolean value is False, whereas in JS it's true
*/
var plb = function(obj) {
return (obj instanceof Array && obj.length == 0)
? false
: Boolean(obj);
};
//=============================================================================
// Date masks
//=============================================================================
// Every mask is 7 days longer to handle cross-year weekly periods.
var M366MASK = [].concat(
repeat(1, 31), repeat(2, 29), repeat(3, 31),
repeat(4, 30), repeat(5, 31), repeat(6, 30),
repeat(7, 31), repeat(8, 31), repeat(9, 30),
repeat(10, 31), repeat(11, 30), repeat(12, 31),
repeat(1, 7)
);
var M365MASK = [].concat(M366MASK);
var
M29 = range(1, 30),
M30 = range(1, 31),
M31 = range(1, 32);
var MDAY366MASK = [].concat(
M31, M29, M31,
M30, M31, M30,
M31, M31, M30,
M31, M30, M31,
M31.slice(0, 7)
);
var MDAY365MASK = [].concat(MDAY366MASK);
M29 = range(-29, 0);
M30 = range(-30, 0);
M31 = range(-31, 0);
var NMDAY366MASK = [].concat(
M31, M29, M31,
M30, M31, M30,
M31, M31, M30,
M31, M30, M31,
M31.slice(0, 7)
);
var NMDAY365MASK = [].concat(NMDAY366MASK);
var M366RANGE = [0,31,60,91,121,152,182,213,244,274,305,335,366];
var M365RANGE = [0,31,59,90,120,151,181,212,243,273,304,334,365];
var WDAYMASK = (function() {
for (var wdaymask = [], i = 0; i < 55; i++) {
wdaymask = wdaymask.concat(range(7));
}
return wdaymask;
}());
M29 = M30 = M31 = null;
M365MASK = M365MASK.slice(0, 58).concat(M365MASK.slice(59, M365MASK.length));
MDAY365MASK = MDAY365MASK.slice(0, 58).concat(MDAY365MASK.slice(59));
NMDAY365MASK = NMDAY365MASK.slice(0, 30).concat(NMDAY365MASK.slice(31));
//=============================================================================
// Weekday
//=============================================================================
var Weekday = function(weekday, n) {
if (n === 0) {
throw 'Can\'t create weekday with n == 0';
}
this.weekday = weekday;
this.n = n;
};
Weekday.prototype = {
// __call__ - Cannot call the object directly, do it through
// e.g. RRule.TH.clone(-1) instead,
clone: function(n) {
return this.n == n ? this : new Weekday(this.weekday, n);
},
// __eq__
equals: function(other) {
return this.weekday == other.weekday && this.n == other.n;
},
// __repr__
toString: function() {
var s = ['MO', 'TU', 'WE', 'TH', 'FR', 'SA', 'SU'][this.weekday];
if (this.n) {
s = (this.n > 0 ? '+' : '') + String(this.n) + s;
}
return s;
},
getJsWeekday: function() {
return this.weekday == 6 ? 0 : this.weekday + 1;
}
};
//=============================================================================
// RRule
//=============================================================================
/**
*
* @param {String} freq - one of RRule.YEARLY, RRule.MONTHLY, ...
* @param {Object?} options - see <http://labix.org/python-dateutil/#head-cf004ee9a75592797e076752b2a889c10f445418>
* @constructor
*/
var RRule = function(freq, options) {
// RFC string
this._string = null;
this._cache = {
all: false,
before: [],
after: [],
between: []
};
var defaults = {
cache: true,
dtstart: null,
interval: 1,
wkst: 0,
count: null,
until: null,
bysetpos: null,
bymonth: null,
bymonthday: null,
byyearday: null,
byweekno: null,
byweekday: null,
byhour: null,
byminute: null,
bysecond: null,
// not implemented:
byeaster: null
};
var invalid = _(options)
.chain()
.keys()
.reject(function(name){
return _.has(defaults, name)
})
.value();
if (invalid.length) {
throw 'Invalid options: ' + invalid.join(', ')
}
// used by toString()
this.origOptions = _.clone(options);
var opts;
this.freq = freq;
this.options = opts = _.extend(defaults, options);
if (opts.byeaster !== null) {
throw new Error('byeaster not implemented');
}
if (!opts.dtstart) {
opts.dtstart = new Date();
opts.dtstart.setMilliseconds(0);
}
if (opts.wkst === null) {
opts.wkst = RRule.MO.weekday;
} else if (typeof opts.wkst == 'number') {
// cool, just keep it like that
} else {
opts.wkst = opts.wkst.weekday;
}
if (opts.bysetpos !== null) {
if (typeof opts.bysetpos == 'number') {
opts.bysetpos = [opts.bysetpos];
}
for (var i = 0; i < opts.bysetpos.length; i++) {
var v = opts.bysetpos[i];
if (v == 0 || !(-366 <= v && v <= 366)) {
throw 'bysetpos must be between 1 and 366, or between -366 and -1';
}
}
}
if (!(plb(opts.byweekno) || plb(opts.byyearday)
|| plb(opts.bymonthday) || opts.byweekday !== null
|| opts.byeaster !== null))
{
switch (this.freq) {
case RRule.YEARLY:
if (!opts.bymonth) {
opts.bymonth = opts.dtstart.getMonth() + 1;
}
opts.bymonthday = opts.dtstart.getDate();
break;
case RRule.MONTHLY:
opts.bymonthday = opts.dtstart.getDate();
break;
case RRule.WEEKLY:
opts.byweekday = dateutil.getWeekday(
opts.dtstart);
break;
}
}
// bymonth
if (opts.bymonth !== null
&& !(opts.bymonth instanceof Array)) {
opts.bymonth = [opts.bymonth];
}
// byyearday
if (opts.byyearday !== null
&& !(opts.byyearday instanceof Array)) {
opts.byyearday = [opts.byyearday];
}
// bymonthday
if (opts.bymonthday === null) {
opts.bymonthday = [];
opts.bynmonthday = [];
} else if (opts.bymonthday instanceof Array) {
var bymonthday = [], bynmonthday = [];
for (i = 0; i < opts.bymonthday.length; i++) {
var v = opts.bymonthday[i];
if (v > 0) {
bymonthday.push(v);
} else if (v < 0) {
bynmonthday.push(v);
}
}
opts.bymonthday = bymonthday;
opts.bynmonthday = bynmonthday;
} else {
if (opts.bymonthday < 0) {
opts.bynmonthday = [opts.bymonthday];
opts.bymonthday = [];
} else {
opts.bynmonthday = [];
opts.bymonthday = [opts.bymonthday];
}
}
// byweekno
if (opts.byweekno !== null
&& !(opts.byweekno instanceof Array)) {
opts.byweekno = [opts.byweekno];
}
// byweekday / bynweekday
if (opts.byweekday === null) {
opts.bynweekday = null;
} else if (typeof opts.byweekday == 'number') {
opts.byweekday = [opts.byweekday];
opts.bynweekday = null;
} else if (opts.byweekday instanceof Weekday) {
if (!opts.byweekday.n || this.freq > RRule.MONTHLY) {
opts.byweekday = [opts.byweekday.weekday];
opts.bynweekday = null;
} else {
opts.bynweekday = [
[opts.byweekday.weekday,
opts.byweekday.n]
];
opts.byweekday = null;
}
} else {
var byweekday = [], bynweekday = [];
for (i = 0; i < opts.byweekday.length; i++) {
var wday = opts.byweekday[i];
if (typeof wday == 'number') {
byweekday.push(wday);
} else if (!wday.n || this.freq > RRule.MONTHLY) {
byweekday.push(wday.weekday);
} else {
bynweekday.push([wday.weekday, wday.n]);
}
}
opts.byweekday = plb(byweekday) ? byweekday : null;
opts.bynweekday = plb(bynweekday) ? bynweekday : null;
}
// byhour
if (opts.byhour === null) {
opts.byhour = (this.freq < RRule.HOURLY)
? [opts.dtstart.getHours()]
: null;
} else if (typeof opts.byhour == 'number') {
opts.byhour = [opts.byhour];
}
// byminute
if (opts.byminute === null) {
opts.byminute = (this.freq < RRule.MINUTELY)
? [opts.dtstart.getMinutes()]
: null;
} else if (typeof opts.byminute == 'number') {
opts.byminute = [opts.byminute];
}
// bysecond
if (opts.bysecond === null) {
opts.bysecond = (this.freq < RRule.SECONDLY)
? [opts.dtstart.getSeconds()]
: null;
} else if (typeof opts.bysecond == 'number') {
opts.bysecond = [opts.bysecond];
}
if (this.freq >= RRule.HOURLY) {
this.timeset = null;
} else {
this.timeset = [];
for (i = 0; i < opts.byhour.length; i++) {
var hour = opts.byhour[i];
for (var j = 0; j < opts.byminute.length; j++) {
var minute = opts.byminute[j];
for (var k = 0; k < opts.bysecond.length; k++) {
var second = opts.bysecond[k];
// python:
// datetime.time(hour, minute, second,
// tzinfo=self._tzinfo))
this.timeset.push(new dateutil.Time(hour, minute, second));
}
}
}
dateutil.sort(this.timeset);
}
};
//}}}
// RRule class 'constants'
RRule.FREQUENCIES = [
'YEARLY', 'MONTHLY', 'WEEKLY', 'DAILY',
'HOURLY', 'MINUTELY', 'SECONDLY'
];
RRule.YEARLY = 0;
RRule.MONTHLY = 1;
RRule.WEEKLY = 2;
RRule.DAILY = 3;
RRule.HOURLY = 4;
RRule.MINUTELY = 5;
RRule.SECONDLY = 6;
RRule.MO = new Weekday(0);
RRule.TU = new Weekday(1);
RRule.WE = new Weekday(2);
RRule.TH = new Weekday(3);
RRule.FR = new Weekday(4);
RRule.SA = new Weekday(5);
RRule.SU = new Weekday(6);
RRule.fromText = function(text, dtstart, language) {
return getnlp().fromText(text, dtstart, language)
}
RRule.prototype = {
/**
* @param {Function} iterator - optional function that will be called
* on each date that is added. It can return false
* to stop the iteration.
* @return Array containing all recurrences.
*/
all: function(iterator) {
if (iterator) {
return this._iter(new CallbackIterResult('all', {}, iterator));
} else {
var result = this._cacheGet('all');
if (result === false) {
result = this._iter(new IterResult('all', {}));
this._cacheAdd('all', result);
}
return result;
}
},
/**
* Returns all the occurrences of the rrule between after and before.
* The inc keyword defines what happens if after and/or before are
* themselves occurrences. With inc == True, they will be included in the
* list, if they are found in the recurrence set.
* @return Array
*/
between: function(after, before, inc, iterator) {
var args = {
before: before,
after: after,
inc: inc
}
if (iterator) {
return this._iter(
new CallbackIterResult('between', args, iterator));
} else {
var result = this._cacheGet('between', args);
if (result === false) {
result = this._iter(new IterResult('between', args));
this._cacheAdd('between', result, args);
}
return result;
}
},
/**
* Returns the last recurrence before the given datetime instance.
* The inc keyword defines what happens if dt is an occurrence.
* With inc == True, if dt itself is an occurrence, it will be returned.
* @return Date or null
*/
before: function(dt, inc) {
var args = {
dt: dt,
inc: inc
},
result = this._cacheGet('before', args);
if (result === false) {
result = this._iter(new IterResult('before', args));
this._cacheAdd('before', result, args);
}
return result;
},
/**
* Returns the first recurrence after the given datetime instance.
* The inc keyword defines what happens if dt is an occurrence.
* With inc == True, if dt itself is an occurrence, it will be returned.
* @return Date or null
*/
after: function(dt, inc) {
var args = {
dt: dt,
inc: inc
},
result = this._cacheGet('after', args);
if (result === false) {
result = this._iter(new IterResult('after', args));
this._cacheAdd('after', result, args);
}
return result;
},
/**
* Returns the number of recurrences in this set. It will have go trough
* the whole recurrence, if this hasn't been done before.
*/
count: function() {
return this.all().length;
},
/**
* Converts the rrule into its string representation
* @see <http://www.ietf.org/rfc/rfc2445.txt>
* @return String
*/
toString: function() {
var attrs = [], key, keys, value,
origValue, currentValue, strValues;
if (this._string) {
return this._string;
}
keys = [
'byhour', 'byminute', 'bymonth',
'bymonthday', 'bysecond', 'bysetpos',
'byweekday', 'byweekno', 'byyearday',
'count', 'interval', 'until', 'wkst'
];
attrs.push(['FREQ', RRule.FREQUENCIES[this.freq]]);
for (var i = 0; i < keys.length; i++) {
key = keys[i];
// Only attributes specified in the options argument
// passed to the constructor will be included in the string
// representation
if (typeof this.origOptions[key] == 'undefined') {
continue;
}
// Do not modify the currentValue array, use this instead
// to store string values
strValues = [];
// Some values are taken from the original options array
// (this.origOptions), and some from the modified version
// (this.options).
currentValue = this.options[key];
origValue = this.origOptions[key];
key = key.toUpperCase();
switch (key) {
case 'WKST':
value = new Weekday(currentValue).toString();
break;
case 'BYWEEKDAY':
key = 'BYDAY';
// XXX: always use origValue, this won't work as expected
// when byweekday contains +n and also -n
value = (currentValue === null)
? this.options.bynweekday
: currentValue;
for (var wday, j = 0; j < value.length; j++) {
wday = value[j];
if (wday instanceof Array) {
wday = new Weekday(wday[0], wday[1]);
} else {
wday = new Weekday(wday);
}
strValues[j] = wday.toString();
}
value = strValues;
break;
case'UNTIL':
value = dateutil.timeToUntilString(currentValue);
break;
default:
if (origValue instanceof Array) {
for (var j = 0; j < origValue.length; j++) {
strValues[j] = String(origValue[j]);
}
value = strValues;
} else {
value = String(origValue);
}
}
attrs.push([key, value]);
}
var strings = [];
for (var i = 0; i < attrs.length; i++) {
var attr = attrs[i];
strings.push(attr[0] + '=' + attr[1].toString());
}
this._string = strings.join(';');
return this._string;
},
/**
* Will convert all rules described in nlp:ToText
* to text.
*/
toText: function(today, today, gettext, language) {
if (!_.has(this, '_text')) {
this._text = getnlp().toText(this, today, gettext, language);
}
return this._text;
},
isFullyConvertibleToText: function() {
return getnlp().isFullyConvertible(this)
},
/**
* @param {String} what - all/before/after/between
* @param {Array,Date} value - an array of dates, one date, or null
* @param {Object?} args - _iter arguments
*/
_cacheAdd: function(what, value, args) {
if (!this.options.cache) return;
if (value) {
value = (value instanceof Date)
? dateutil.clone(value)
: dateutil.cloneDates(value);
}
if (what == 'all') {
this._cache.all = value;
} else {
args._value = value;
this._cache[what].push(args);
}
},
/**
* @return false - not in the cache
* null - cached, but zero occurrences (before/after)
* Date - cached (before/after)
* [] - cached, but zero occurrences (all/between)
* [Date1, DateN] - cached (all/between)
*/
_cacheGet: function(what, args) {
if (!this.options.cache) {
return false;
}
var cached = false;
if (what == 'all') {
cached = this._cache.all;
} else {
// Let's see whether we've already called the
// 'what' method with the same 'args'
loopItems:
for (var item, i = 0; i < this._cache[what].length; i++) {
item = this._cache[what][i];
for (var k in args) {
if (args.hasOwnProperty(k)
&& String(args[k]) != String(item[k])) {
continue loopItems;
}
}
cached = item._value;
break;
}
}
if (!cached && this._cache.all) {
// Not in the cache, but we already know all the occurrences,
// so we can find the correct dates from the cached ones.
var iterResult = new IterResult(what, args);
for (var i = 0; i < this._cache.all.length; i++) {
if (!iterResult.accept(this._cache.all[i])) {
break;
}
}
cached = iterResult.getValue();
this._cacheAdd(what, cached, args);
}
return cached instanceof Array
? dateutil.cloneDates(cached)
: (cached instanceof Date
? dateutil.clone(cached)
: cached);
},
/**
* @return a RRule instance with the same freq and options
* as this one (cache is not cloned)
*/
clone: function() {
return new RRule(this.freq, this.origOptions);
},
_iter: function(iterResult) {
/* Since JavaScript doesn't have the python's yield operator (<1.7),
we use the IterResult object that tells us when to stop iterating.
*/
var dtstart = this.options.dtstart;
var
year = dtstart.getFullYear(),
month = dtstart.getMonth() + 1,
day = dtstart.getDate(),
hour = dtstart.getHours(),
minute = dtstart.getMinutes(),
second = dtstart.getSeconds(),
weekday = dateutil.getWeekday(dtstart),
yearday = dateutil.getYearDay(dtstart);
// Some local variables to speed things up a bit
var
freq = this.freq,
interval = this.options.interval,
wkst = this.options.wkst,
until = this.options.until,
bymonth = this.options.bymonth,