forked from andrewplummer/Sugar
-
Notifications
You must be signed in to change notification settings - Fork 0
/
range.js
637 lines (576 loc) · 15.9 KB
/
range.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
'use strict';
/***
* @module Range
* @description Date, Number, and String ranges that can be manipulated and compared,
* or enumerate over specific points within the range.
*
***/
var DURATION_UNITS = 'year|month|week|day|hour|minute|second|millisecond';
var DURATION_REG = RegExp('(\\d+)?\\s*('+ DURATION_UNITS +')s?', 'i');
var MULTIPLIERS = {
'Hours': 60 * 60 * 1000,
'Minutes': 60 * 1000,
'Seconds': 1000,
'Milliseconds': 1
};
var PrimitiveRangeConstructor = function(start, end) {
return new Range(start, end);
};
function Range(start, end) {
this.start = cloneRangeMember(start);
this.end = cloneRangeMember(end);
}
function getRangeMemberNumericValue(m) {
return isString(m) ? m.charCodeAt(0) : m;
}
function getRangeMemberPrimitiveValue(m) {
if (m == null) return m;
return isDate(m) ? m.getTime() : m.valueOf();
}
function getPrecision(n) {
var split = periodSplit(n.toString());
return split[1] ? split[1].length : 0;
}
function getGreaterPrecision(n1, n2) {
return max(getPrecision(n1), getPrecision(n2));
}
function cloneRangeMember(m) {
if (isDate(m)) {
return new Date(m.getTime());
} else {
return getRangeMemberPrimitiveValue(m);
}
}
function isValidRangeMember(m) {
var val = getRangeMemberPrimitiveValue(m);
return (!!val || val === 0) && valueIsNotInfinite(m);
}
function valueIsNotInfinite(m) {
return m !== -Infinity && m !== Infinity;
}
function rangeIsValid(range) {
return isValidRangeMember(range.start) &&
isValidRangeMember(range.end) &&
typeof range.start === typeof range.end;
}
function rangeEvery(range, step, countOnly, fn) {
var increment,
precision,
dio,
unit,
start = range.start,
end = range.end,
inverse = end < start,
current = start,
index = 0,
result = [];
if (!rangeIsValid(range)) {
return [];
}
if (isFunction(step)) {
fn = step;
step = null;
}
step = step || 1;
if (isNumber(start)) {
precision = getGreaterPrecision(start, step);
increment = function() {
return incrementNumber(current, step, precision);
};
} else if (isString(start)) {
increment = function() {
return incrementString(current, step);
};
} else if (isDate(start)) {
dio = getDateIncrementObject(step);
step = dio[0];
unit = dio[1];
increment = function() {
return incrementDate(current, step, unit);
};
}
// Avoiding infinite loops
if (inverse && step > 0) {
step *= -1;
}
while(inverse ? current >= end : current <= end) {
if (!countOnly) {
result.push(current);
}
if (fn) {
fn(current, index, range);
}
current = increment();
index++;
}
return countOnly ? index - 1 : result;
}
function getDateIncrementObject(amt) {
var match, val, unit;
if (isNumber(amt)) {
return [amt, 'Milliseconds'];
}
match = amt.match(DURATION_REG);
val = +match[1] || 1;
unit = simpleCapitalize(match[2].toLowerCase());
if (unit.match(/hour|minute|second/i)) {
unit += 's';
} else if (unit === 'Year') {
unit = 'FullYear';
} else if (unit === 'Week') {
unit = 'Date';
val *= 7;
} else if (unit === 'Day') {
unit = 'Date';
}
return [val, unit];
}
function incrementDate(src, amount, unit) {
var mult = MULTIPLIERS[unit], d;
if (mult) {
d = new Date(src.getTime() + (amount * mult));
} else {
d = new Date(src);
callDateSet(d, unit, callDateGet(src, unit) + amount);
}
return d;
}
function incrementString(current, amount) {
return chr(current.charCodeAt(0) + amount);
}
function incrementNumber(current, amount, precision) {
return withPrecision(current + amount, precision);
}
function rangeClamp(range, obj) {
var clamped,
start = range.start,
end = range.end,
min = end < start ? end : start,
max = start > end ? start : end;
if (obj < min) {
clamped = min;
} else if (obj > max) {
clamped = max;
} else {
clamped = obj;
}
return cloneRangeMember(clamped);
}
defineOnPrototype(Range, {
/***
* @method toString()
* @returns String
* @short Returns a string representation of the range.
*
* @example
*
* Number.range(1, 5).toString() -> 1..5
* janToMay.toString() -> January 1, xxxx..May 1, xxxx
*
***/
'toString': function() {
return rangeIsValid(this) ? this.start + '..' + this.end : 'Invalid Range';
},
/***
* @method isValid()
* @returns Boolean
* @short Returns true if the range is valid, false otherwise.
*
* @example
*
* janToMay.isValid() -> true
* Number.range(NaN, NaN).isValid() -> false
*
***/
'isValid': function() {
return rangeIsValid(this);
},
/***
* @method span()
* @returns Number
* @short Returns the span of the range. If the range is a date range, the
* value is in milliseconds.
* @extra The span includes both the start and the end.
*
* @example
*
* Number.range(5, 10).span() -> 6
* Number.range(40, 25).span() -> 16
* janToMay.span() -> 10368000001 (or more depending on leap year)
*
***/
'span': function() {
var n = getRangeMemberNumericValue(this.end) - getRangeMemberNumericValue(this.start);
return rangeIsValid(this) ? abs(n) + 1 : NaN;
},
/***
* @method contains(<obj>)
* @returns Boolean
* @short Returns true if <obj> is contained inside the range. <obj> may be a
* value or another range.
*
* @example
*
* Number.range(5, 10).contains(7) -> true
* Number.range(5, 10).contains(2) -> false
* janToMay.contains(mar) -> true
* janToMay.contains(marToAug) -> false
* janToMay.contains(febToApr) -> true
*
***/
'contains': function(obj) {
if (obj == null) return false;
if (obj.start && obj.end) {
return obj.start >= this.start && obj.start <= this.end &&
obj.end >= this.start && obj.end <= this.end;
} else {
return obj >= this.start && obj <= this.end;
}
},
/***
* @method every(<amount>, [fn])
* @returns Array
* @short Iterates through the range by <amount>, calling [fn] for each step.
* @extra Returns an array of each increment visited. For date ranges,
* <amount> can also be a string like `"2 days"`. This will step
* through the range by incrementing a date object by that specific
* unit, and so is generally preferable for vague units such as
* `"2 months"`.
*
* @callback fn
*
* el The element of the current iteration.
* i The index of the current iteration.
* r A reference to the range.
*
* @example
*
* Number.range(2, 8).every(2) -> [2,4,6,8]
* janToMay.every('2 months') -> [Jan 1, Mar 1, May 1]
*
* sepToOct.every('week', function() {
* // Will be called every week from September to October
* })
*
***/
'every': function(amount, fn) {
return rangeEvery(this, amount, false, fn);
},
/***
* @method toArray()
* @returns Array
* @short Creates an array from the range.
* @extra If the range is a date range, every millisecond between the start
* and end dates will be returned. To control this use `every` instead.
*
* @example
*
* Number.range(1, 5).toArray() -> [1,2,3,4,5]
* Date.range('1 millisecond ago', 'now').toArray() -> [1ms ago, now]
*
***/
'toArray': function() {
return rangeEvery(this);
},
/***
* @method union(<range>)
* @returns Range
* @short Returns a new range with the earliest starting point as its start,
* and the latest ending point as its end. If the two ranges do not
* intersect this will effectively remove the "gap" between them.
*
* @example
*
* oneToTen.union(fiveToTwenty) -> 1..20
* janToMay.union(marToAug) -> Jan 1, xxxx..Aug 1, xxxx
*
***/
'union': function(range) {
return new Range(
this.start < range.start ? this.start : range.start,
this.end > range.end ? this.end : range.end
);
},
/***
* @method intersect(<range>)
* @returns Range
* @short Returns a new range with the latest starting point as its start,
* and the earliest ending point as its end. If the two ranges do not
* intersect this will effectively produce an invalid range.
*
* @example
*
* oneToTen.intersect(fiveToTwenty) -> 5..10
* janToMay.intersect(marToAug) -> Mar 1, xxxx..May 1, xxxx
*
***/
'intersect': function(range) {
if (range.start > this.end || range.end < this.start) {
return new Range(NaN, NaN);
}
return new Range(
this.start > range.start ? this.start : range.start,
this.end < range.end ? this.end : range.end
);
},
/***
* @method clone()
* @returns Range
* @short Clones the range.
* @extra Members of the range will also be cloned.
*
* @example
*
* Number.range(1, 5).clone() -> Returns a copy of the range.
*
***/
'clone': function() {
return new Range(this.start, this.end);
},
/***
* @method clamp(<obj>)
* @returns Mixed
* @short Clamps <obj> to be within the range if it falls outside.
*
* @example
*
* Number.range(1, 5).clamp(8) -> 5
* janToMay.clamp(aug) -> May 1, xxxx
*
***/
'clamp': function(obj) {
return rangeClamp(this, obj);
}
});
/*** @namespace Number ***/
defineStatic(sugarNumber, {
/***
* @method range([start], [end])
* @returns Range
* @static
* @short Creates a new number range between [start] and [end]. See `ranges`
* for more.
*
* @example
*
* Number.range(5, 10)
* Number.range(20, 15)
*
***/
'range': PrimitiveRangeConstructor
});
defineInstance(sugarNumber, {
/***
* @method upto(<num>, [step] = 1, [fn])
* @returns Array
* @short Returns an array containing numbers from the number up to <num>.
* @extra Optionally calls [fn] for each number in that array. [step] allows
* multiples other than 1. [fn] can be passed in place of [step].
*
* @callback fn
*
* el The element of the current iteration.
* i The index of the current iteration.
* r A reference to the range.
*
* @example
*
* (2).upto(6) -> [2, 3, 4, 5, 6]
* (2).upto(6, function(n) {
* // This function is called 5 times receiving n as the value.
* });
* (2).upto(8, 2) -> [2, 4, 6, 8]
*
***/
'upto': function(n, num, step, fn) {
return rangeEvery(new Range(n, num), step, false, fn);
},
/***
* @method clamp([start] = Infinity, [end] = Infinity)
* @returns Number
* @short Constrains the number so that it falls on or between [start] and
* [end].
* @extra This will build a range object that has an equivalent `clamp` method.
*
* @example
*
* (3).clamp(50, 100) -> 50
* (85).clamp(50, 100) -> 85
*
***/
'clamp': function(n, start, end) {
return rangeClamp(new Range(start, end), n);
},
/***
* @method cap([max] = Infinity)
* @returns Number
* @short Constrains the number so that it is no greater than [max].
* @extra This will build a range object that has an equivalent `cap` method.
*
* @example
*
* (100).cap(80) -> 80
*
***/
'cap': function(n, max) {
return rangeClamp(new Range(undefined, max), n);
}
});
/***
* @method downto(<num>, [step] = 1, [fn])
* @returns Array
* @short Returns an array containing numbers from the number down to <num>.
* @extra Optionally calls [fn] for each number in that array. [step] allows
* multiples other than 1. [fn] can be passed in place of [step].
*
* @callback fn
*
* el The element of the current iteration.
* i The index of the current iteration.
* r A reference to the range.
*
* @example
*
* (8).downto(3) -> [8, 7, 6, 5, 4, 3]
* (8).downto(3, function(n) {
* // This function is called 6 times receiving n as the value.
* });
* (8).downto(2, 2) -> [8, 6, 4, 2]
*
***/
alias(sugarNumber, 'downto', 'upto');
/*** @namespace String ***/
defineStatic(sugarString, {
/***
* @method range([start], [end])
* @returns Range
* @static
* @short Creates a new string range between [start] and [end]. See `ranges`
* for more.
*
* @example
*
* String.range('a', 'z')
* String.range('t', 'm')
*
***/
'range': PrimitiveRangeConstructor
});
/*** @namespace Date ***/
var FULL_CAPTURED_DURATION = '((?:\\d+)?\\s*(?:' + DURATION_UNITS + '))s?';
// Duration text formats
var RANGE_REG_FROM_TO = /(?:from)?\s*(.+)\s+(?:to|until)\s+(.+)$/i,
RANGE_REG_REAR_DURATION = RegExp('(.+)\\s*for\\s*' + FULL_CAPTURED_DURATION, 'i'),
RANGE_REG_FRONT_DURATION = RegExp('(?:for)?\\s*'+ FULL_CAPTURED_DURATION +'\\s*(?:starting)?\\s*at\\s*(.+)', 'i');
var DateRangeConstructor = function(start, end) {
if (arguments.length === 1 && isString(start)) {
return createDateRangeFromString(start);
}
return new Range(getDateForRange(start), getDateForRange(end));
};
function createDateRangeFromString(str) {
var match, datetime, duration, dio, start, end;
if (sugarDate.get && (match = str.match(RANGE_REG_FROM_TO))) {
start = getDateForRange(match[1].replace('from', 'at'));
end = sugarDate.get(start, match[2]);
return new Range(start, end);
}
if (match = str.match(RANGE_REG_FRONT_DURATION)) {
duration = match[1];
datetime = match[2];
}
if (match = str.match(RANGE_REG_REAR_DURATION)) {
datetime = match[1];
duration = match[2];
}
if (datetime && duration) {
start = getDateForRange(datetime);
dio = getDateIncrementObject(duration);
end = incrementDate(start, dio[0], dio[1]);
} else {
start = str;
}
return new Range(getDateForRange(start), getDateForRange(end));
}
function getDateForRange(d) {
if (isDate(d)) {
return d;
} else if (d == null) {
return new Date();
} else if (sugarDate.create) {
return sugarDate.create(d);
}
return new Date(d);
}
/***
* @method [dateUnit]()
* @returns Number
* @namespace Range
* @short Returns the span of a date range in the given unit.
* @extra Higher order units ("days" and greater) walk the date to avoid
* discrepancies with ambiguity. Lower order units simply subtract the
* start from the end.
*
* @set
* milliseconds
* seconds
* minutes
* hours
* days
* weeks
* months
* years
*
* @example
*
* janToMay.months() -> 4
* janToMay.days() -> 121
* janToMay.hours() -> 2904
* janToMay.minutes() -> 220320
*
***/
function buildDateRangeUnits() {
var methods = {};
forEach(DURATION_UNITS.split('|'), function(unit, i) {
var name = unit + 's', mult, fn;
if (i < 4) {
fn = function() {
return rangeEvery(this, unit, true);
};
} else {
mult = MULTIPLIERS[simpleCapitalize(name)];
fn = function() {
return trunc((this.end - this.start) / mult);
};
}
methods[name] = fn;
});
defineOnPrototype(Range, methods);
}
defineStatic(sugarDate, {
/***
* @method range([start], [end])
* @returns Range
* @static
* @short Creates a new date range between [start] and [end].
* @extra Arguments may be either dates or strings which will be forwarded to
* the date constructor (`create` will be used if present in the build).
* If either [start] or [end] are undefined, they will default to the
* current date. This method also accepts an alternate syntax of a
* single string describing the range in natural language. See `ranges`
* for more.
*
* @example
*
* Date.range(jan, may)
* Date.range('today', 'tomorrow')
* Date.range('now', '5 days ago')
* Date.range('last Monday')
* Date.range('Monday to Friday')
* Date.range('tomorrow from 3pm to 5pm')
* Date.range('1 hour starting at 5pm Tuesday')
*
***/
'range': DateRangeConstructor
});
buildDateRangeUnits();