-
Notifications
You must be signed in to change notification settings - Fork 88
Expand file tree
/
Copy pathdate.js
More file actions
3633 lines (3263 loc) · 87.9 KB
/
date.js
File metadata and controls
3633 lines (3263 loc) · 87.9 KB
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
(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.date = f()}})(function(){var define,module,exports;return (function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i<t.length;i++)o(t[i]);return o}return r})()({1:[function(require,module,exports){
/**
* Expose `Date`
*/
module.exports = require('./lib/parser');
},{"./lib/parser":5}],2:[function(require,module,exports){
/**
* Module Dependencies
*/
var debug = require('debug')('date:date')
/**
* Time constants
*/
var _second = 1000
var _minute = 60 * _second
var _hour = 60 * _minute
var _day = 24 * _hour
var _week = 7 * _day
var _year = 56 * _week
var _daysInMonth = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
/**
* Expose `date`
*/
module.exports = date
/**
* Initialize `date`
*
* @param {Date} offset (optional)
* @return {Date}
* @api publics
*/
function date (offset) {
if (!(this instanceof date)) return new date(offset)
this._changed = {}
this.date = new Date(offset)
}
/**
* Clone the current date
*/
date.prototype.clone = function () {
return new Date(this.date)
}
/**
* Has changed
*
* @param {String} str
* @return {Boolean}
*/
date.prototype.changed = function (str) {
if (this._changed[str] === undefined) return false
return this._changed[str]
}
/**
* add or subtract seconds
*
* @param {Number} n
* @return {date}
*/
date.prototype.second = function (n) {
var seconds = +n * _second
this.update(seconds)
this._changed['seconds'] = true
return this
}
/**
* add or subtract minutes
*
* @param {Number} n
* @return {date}
*/
date.prototype.minute = function (n) {
var minutes = +n * _minute
this.update(minutes)
this._changed['minutes'] = true
return this
}
/**
* add or subtract hours
*
* @param {Number} n
* @return {date}
*/
date.prototype.hour = function (n) {
var hours = +n * _hour
this.update(hours)
this._changed['hours'] = true
return this
}
/**
* add or subtract days
*
* @param {Number} n
* @return {date}
*/
date.prototype.day = function (n) {
var days = +n * _day
this.update(days)
this._changed['days'] = true
return this
}
/**
* add or subtract weeks
*
* @param {Number} n
* @return {date}
*/
date.prototype.week = function (n) {
var weeks = +n * _week
this.update(weeks)
this._changed['weeks'] = true
return this
}
/**
* add or subtract months
*
* @param {Number} n
* @return {Date}
*/
date.prototype.month = function (n) {
var d = this.date
var day = d.getDate()
d.setDate(1)
var month = +n + d.getMonth()
d.setMonth(month)
// Handle dates with less days
var dim = this.daysInMonth(month)
d.setDate(Math.min(dim, day))
return this
}
/**
* get the days in the month
*/
date.prototype.daysInMonth = function (m) {
var dim = _daysInMonth[m]
var leap = leapyear(this.date.getFullYear())
return (1 == m && leap) ? 29 : 28
}
/**
* add or subtract years
*
* @param {Number} n
* @return {date}
*/
date.prototype.year = function (n) {
var yr = this.date.getFullYear()
yr += +n
this.date.setFullYear(yr)
this._changed['years'] = true
return this
}
/**
* Set the time
*
* @param {String} h
* @param {String} m
* @param {String} s
* @return {date}
*/
date.prototype.time = function (h, m, s, meridiem) {
if (h === false) {
h = this.date.getHours()
} else {
h = +h || 0
this._changed['hours'] = h
}
if (m === false) {
m = this.date.getMinutes()
} else {
m = +m || 0
this._changed['minutes'] = m
}
if (s === false) {
s = this.date.getSeconds()
} else {
s = +s || 0
this._changed['seconds'] = s
}
this.date.setHours(h, m, s)
return this
}
/**
* Dynamically create day functions (sunday(n), monday(n), etc.)
*/
var days = ['sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday']
days.forEach(function (day, i) {
date.prototype[days[i]] = function (n) {
this._changed['days'] = true
this.updateDay(i, n)
}
})
/**
* go to day of week
*
* @param {Number} day
* @param {Number} n
* @return {date}
*/
date.prototype.updateDay = function (d, n) {
n = +(n || 1)
var diff = (d - this.date.getDay() + 7) % 7
if (n > 0) --n
diff += (7 * n)
this.update(diff * _day)
return this
}
/**
* Update the date
*
* @param {Number} ms
* @return {Date}
* @api private
*/
date.prototype.update = function (ms) {
this.date = new Date(this.date.getTime() + ms)
return this
}
/**
* leap year
*
* @param {Number} yr
* @return {Boolean}
*/
function leapyear (yr) {
return (yr % 4 === 0 && yr % 100 !== 0) || yr % 400 === 0
}
},{"debug":10}],3:[function(require,module,exports){
module.exports={
"op": {
"plus": ["and", "plus", "+", "add", "on"],
"minus": ["minus", "subtract"],
"times": ["times", "multiply"],
"divide": ["divide"]
},
"o": {
"plus": ["at", "in", "past", "late", "later", "after", "next", "from", "start", "starting", "since", "coming"],
"minus": ["last", "minus", "subtract", "ago", "before", "from"]
},
"n": {
"0.25": ["quarter"],
"0.5": ["half", "1/2", "half an"],
"0": ["zero"],
"1": ["one", "a", "an", "first"],
"2": ["two", "second"],
"3": ["three", "third"],
"4": ["four", "fourth"],
"5": ["five", "fifth"],
"6": ["six", "sixth"],
"7": ["seven", "seventh"],
"8": ["eight", "eighth"],
"9": ["nine", "ninth"],
"10": ["ten", "tenth"],
"11": ["eleven", "eleventh"],
"12": ["twelve", "twelveth"],
"13": ["thirteen", "thirteenth"],
"14": ["fourteen", "fourteenth"],
"15": ["fifteen", "fifteenth"],
"16": ["sixteen", "sixteenth"],
"17": ["seventeen", "seventeenth"],
"18": ["eighteen", "eighteenth"],
"19": ["nineteen", "nineteenth"],
"20": ["twenty", "twentieth"],
"30": ["thirty", "thirtieth"],
"40": ["fourty", "fourtieth"],
"50": ["fifty", "fiftieth"],
"60": ["sixty", "sixtieth"],
"70": ["seventy", "seventieth"],
"80": ["eighty", "eightieth"],
"90": ["ninety", "ninetieth"],
"100": ["hundred", "hundreds", "hundredth"],
"1000": ["thousand", "thousands", "thousandth", "k", "K"]
},
"t": {
},
"dt": {
"s": ["second", "seconds", "s", "sec", "secs"],
"m": ["minute", "minutes", "m", "min", "mins"],
"h": ["hour", "hours", "h", "hr", "hrs"],
"d": ["day", "days", "d", "dai"],
"w": ["week", "weeks", "w", "wk", "wks"],
"M": ["month", "months", "monthes", "M", "mo", "moon", "moons"],
"y": ["year", "years", "y", "yr", "yrs"]
},
"T": {
"t:,dt:=3h": ["later", "soon"],
"t:=1d,dt:": ["st", "nd", "rd", "th", "st day", "nd day", "rd day", "th day"],
"t:,dt:1w": ["st week", "nd week", "rd week", "th week"],
"t:,dt:14d": ["day", "fortnight"],
"t:=0h=0m=0s1mer,dt:": ["pm", "p.m", "p.m.", "noon"],
"t:,dt:1d": ["tomorrow", "tmr"],
"t:,dt:-1d": ["yesterday", "ytd"],
"t:,0dt:": ["today"],
"t:=2h=0m=0s1mer,dt:": ["afternoon"],
"t:=6h=0m=0s0mer,dt:": ["dawn"],
"t:=7h=0m=0s0mer,dt:": ["am", "a.m", "a.m."],
"t:=7h=0m=0s1mer,dt:": ["evening"],
"t:=8h=0m=0s0mer,dt:": ["morning"],
"t:=9h=0m=0s1mer,dt:": ["tonight", "night"],
"t:=0h=0m=0s0mer,dt:1d": ["midnight"],
"t:,dt:=0w0wd": ["sunday", "sun"],
"t:,dt:=0w1wd": ["monday", "mon"],
"t:,dt:=0w2wd": ["tuesday", "tue", "tues"],
"t:,dt:=0w3wd": ["wednesday", "wed"],
"t:,dt:=0w4wd": ["thursday", "thu", "thur", "thurs"],
"t:,dt:=0w5wd": ["friday", "fri"],
"t:,dt:=0w6wd": ["saturday", "sat"],
"t:1M=1d,dt:": ["january", "jan"],
"t:2M=1d,dt:": ["february", "feb"],
"t:3M=1d,dt:": ["march", "mar"],
"t:4M=1d,dt:": ["april", "apr"],
"t:5M=1d,dt:": ["may"],
"t:6M=1d,dt:": ["june", "jun"],
"t:7M=1d,dt:": ["july", "jul"],
"t:8M=1d,dt:": ["august", "aug"],
"t:9M=1d,dt:": ["september", "sept", "sep"],
"t:10M=1d,dt:": ["october", "oct"],
"t:11M=1d,dt:": ["november", "nov"],
"t:12M=1d,dt:": ["december", "dec"],
"t:12M25d,dt:": ["christmas"]
},
"f": {
"1": ["once"],
"2": ["twice"]
}
}
},{}],4:[function(require,module,exports){
// Production rule module for the CFG
// !leap year
// !proper carry considering # of days per month
/**
* Module Dependencies
*/
var _ = require('./subdash')
var util = require('./util')
var symbol = require('./symbol')
var tokenize = require('./tokenize')
/**
* Export `norm`
*/
module.exports = norm
// a partial implementation of norm
/**
* Preprocess a string using the human language for time CFG, return a triple of original str, preprocessed tokens, and the normal forms (extracted dates in normal forms)
*/
function norm (str, offset) {
try {
// Production rules: CFG algorithm for human language for time
var tokObj = tokenize(str)
// console.log('p#0: parse normal forms', tokObj)
var syms = pickTokens(tokObj.symbols) || []
// console.log('p#0: remove nulls, pick tokens', syms)
syms = reduce(syms, ['n', 'n'])
// console.log('p#1: arithmetics: <n1>[<op>]<n2> ~ <n>, + if n1 > n2, * else', syms)
syms = nTnRedistribute(syms)
// console.log('p#2: redistribute, <n1><T1>[<op>]<n2><!T2> ~ <n1>[<op>]<n2> <T1>', syms)
syms = reduce(syms, ['o', 'o'])
// console.log('p#3: <o><o> ~ <o>*<o>', syms)
// preprocessing ends, now format output
var restored = restoreTokens(syms, tokObj)
return restored
} catch (e) {
return {
str: str,
tokens: [],
normals: []
}
}
}
/**
* format a preprocessed array of symbols back into string, using some info from tokObj
*/
function restoreTokens (syms, tokObj) {
var tokens = [],
normals = [],
tokensOut = tokObj.tokensOut,
tokensIn = tokObj.tokensIn
syms = util.removeTnPlus(syms)
for (var i = 0; i < syms.length; i++) {
var s = syms[i],
sName = util.sName(s),
token = ''
switch (sName) {
case 'n':
// if token is already numeric, use it
token = (s.token.match(/^\s*[\d\.\-\+]+\s*$/)) ? s.token.trim() : s.value.toString()
break
case 'T':
// handles shits like 1 am ~ t:1h00m,dt:, am (token returned)
token = restoreNormal(s)
break
default:
// the other cases like op, o, cron, range
token = s.token.toString()
}
// extract the protected normal string
if (typeof token == 'string') {
tokens.push(token)
} else {
// get protected normal forms
normals.push(token.normal)
}
}
return {
tokens: tokens,
str: tokens.join(' ').replace(/\s+/g, ' '),
normals: normals
}
}
/**
* Given a T symbol, try to restore its normal form (return wrapped in JSON if it's a complete date string {normal: <normal string>}), or just return the plain string as token
*/
function restoreNormal (T) {
var token = T.token
if (token.match(util.reT)) {
// if it is normal form, convert back into the normal1 or normal2 strings
var split = util.splitT(token)
if (_.includes(split, undefined)) {
// if it's normal2 form
// either it's a date or time
var dateArr = split.slice(0, 3),
timeArr = split.slice(3)
if (timeArr[0] != undefined) {
// check time first, it's first signature (hour) is defined
// return hh:mm
return util.TtoStdT(token).match(/(\d+\:\d+)/)[1]
} else {
// else it's a date, parse arr and return complete stdT instead
// return wrapped in JSON if it's a complete date string
return { normal: util.TtoStdT(token) }
}
} else {
// if it's normal1 form, use TtoStd
// return wrapped in JSON if it's a complete date string
return { normal: util.TtoStdT(token) }
}
} else if (!util.has_t(T) && util.has_dt(T) && util.has_pureTimeUnit(T)) {
// handle pure dt: T that are purel displacement, e.g. week, fortnight
var dtStr = '',
units = _.keys(T.dt),
dt = T.dt
// accumulate dtStr
for (var i = 0; i < units.length; i++) {
var u = units[i],
kval = parseFloat(dt[u]),
// set number has default, or is 0, 1
numStr = (kval != dt[u] || kval == 0 || Math.abs(kval) == 1) ? '' : dt[u].toString() + ' '
// set canon from lemma only if it exists, and key is word, else use u
var canon = u
if (T.canon != undefined) {
// and if it's also a timeUnit
canon = T.canon
} else {
// get the lemma for u, its canon and key
var lemma = util.lemma(u),
lemmaCanon = lemma.canon,
lemmaKey = lemma.value
if (lemmaKey && lemmaKey.match(/^\w+$/)) { canon = lemmaCanon }
}
// set the units, number, and canonical form of the unit
dtStr = dtStr + numStr + canon + ' '
}
return dtStr
} else {
// else it's just plain english, return
return token
}
}
// var fakes = { t: { h: '1', m: '00' }, dt: {}, token: 't:1h00m,dt:' }
// var fakes = { t: { M: '12', d: '25', m: '00' }, dt: {}, token: 't:12M25d00m,dt:' }
// console.log(restoreNormal(fakes))
/**
* !Backburner for future extension: Main method: Run the CFG algorithm to parse the string, return JSON of {input, output, diffStr}. Normalize the string before Matt's algorithm runs it.
* @example
* var str = 'having lunch today at 3 hours after 9am'
* norm(str)
* // => { input: 'having lunch today at 3 hours after 9am',
* output: '2016-03-04T05:00:09Z',
* difference: 'having lunch' }
*/
function CFGproduce (str, offset) {
// try all the below till all is elegantly fixed
var diffStr = str,
finalStr = null,
output = str
// Production rules: CFG algorithm for human language for time
// p#0: tokenize, remove nulls, pick tokens
var tokObj = tokenize(str)
var syms = pickTokens(tokObj.symbols)
// console.log('p#0: parse normal forms, remove nulls, pick tokens', tokObj)
try {
syms = reduce(syms, ['n', 'n'])
// console.log('p#1: arithmetics: <n1>[<op>]<n2> ~ <n>, + if n1 > n2, * else', syms)
syms = nTnRedistribute(syms)
// console.log('p#2: redistribute, <n1><T1>[<op>]<n2><!T2> ~ <n1>[<op>]<n2> <T1>', syms)
output = util.tokenToStr(syms)
// !okay replace back the normal forms in the str
// // !Till future completion: Mute from below
// syms = reduce(syms, ['n', 'T'])
// // console.log('p#3: <n>[<op>]<T> ~ <T>, * if dt, + if t', syms)
// syms = reduce(syms, ['T', 'T'])
// // console.log('p#4: <T>[<op>]<T> ~ <T>', syms)
// syms = nDefTSyms(syms)
// // console.log('p#5: defaulter <o> <n> <o> ~ <o> <T> <o>, d defaults to t:h', syms)
// syms = reduce(syms, ['o', 'o'])
// // console.log('p#6: <o><o> ~ <o>*<o>', syms)
// syms = autoHourModding(syms)
// syms = weekModding(syms, offset)
// // console.log('p#7: modding: meridiem, weeks', syms)
// syms = optReduce(syms, ['T', 'T'], ['o'], null, symbol(util.nowT(offset)))
// // console.log('p#8: <T><o><T> ~ <T>', syms)
// // !future:
// // syms = reduce(syms, ['T'], ['r'])
// // syms = reduce(syms, ['f', 'T', 'rT'], ['c'])
// console.log('tokObj', tokObj)
syms = finalizeT(syms, offset)
// console.log('p#9: finalizeT with origin', syms)
finalStr = symsToStdT(syms, offset)
// console.log('finalStr', finalStr)
} catch (e) {}
// extract the tokens for difference string later
// diffStr = util.unparsedStr(tokObj.str, tokObj.symbols)
// console.log('diffStr', diffStr)
// !convert dt into proper terms
return {
input: str,
// output: new Date(finalStr),
output: output,
difference: diffStr
}
}
/**
* Production rule #0: pick tokens, remove nulls.
* 1. break into chunks of arrs delimited by triple-null-or-more
* 2. reorder chunks by arr length
* 3.1 init candidate = []
* 3.2 pull and push the chunks not containing <T> into candidate
* 3.3 pull and push the chunks containing <T> into candidate
* 4. pick the last candidate
*/
function pickTokens (syms) {
// 1. 2. 3.
var delimited = util.delimSyms(syms),
chunks = util.splitSyms(delimited, 'trinull'),
candidates = util.orderChunks(chunks)
// 4.
return candidates.pop()
}
/**
* Reduce an array of symbols with binary operations between permissible symbols.
* @param {Array} syms Array of input symbols
* @param {Array} varArr String names of permissible variables.
* @param {Array} opArr String names of permissible operations.
* @return {Array} The reduced result.
*/
function reduce (syms, varArr, opArr) {
if (syms.length < 2) {
return syms
}
// the operator arrays
var opArr = opArr || ['op']
// endmark for handling last symbol
syms.push('null')
// the result, past-pointer(previous non-null symbol), default-op, current-op, and whether current-op is inter-symbol op, i.e. will not be used up
var res = [],
past = null,
defOp = null,
op = defOp,
interOp = false
for (var i = 0; i < syms.length; i++) {
var s = syms[i]
if (!past || !s) {
// edge case or null
if (i == 0) { past = s; }
} else if (util.isSym(s, opArr)) {
// s is an op. mark op as won't be used yet
op = s
interOp = true
// the nDefT for when past = 'n', s = 'o'
} else if (util.isSym(past, [varArr[0]]) && util.isSym(s, [varArr[1]])) {
// s and past are operable variables specified by varArr
past = execOp(past, op, s)
// reset after op is used
op = defOp
interOp = false
} else {
// no further legal operation made, push and continue
// change of class, past is finalized, push to res
res.push(past)
if (Array.isArray(past)) {
// if past was returned from execOp as array (not executed), then flatten it and dont push op to res, since it's already included in op
res = _.flatten(res)
} else {
// if inter-op (not used), push a clone (prevent overwrite later)
if (interOp) { res.push(symbol(op.value)) }
}
// reset
op = defOp
interOp = false
past = s
}
}
return res
}
/**
* Optional reduce: similar to reduce() but either argument is optional.
* algorithm: return a T
* 1. for each t, dt, do:
* 2. for each key in union of keys for Lt, Rt, do:
* 3. _Rt = _Rt op _Lt
* @param {Array} syms Array of input symbols
* @param {Array} varArr String names of permissible variables.
* @param {Array} opArr String names of permissible operations.
* @param {symbol} Ldef default for left argument
* @param {symbol} Rdef default for right argument
* @return {Array} The reduced result.
*/
function optReduce (syms, varArr, opArr, Ldef, Rdef) {
if (syms.length < 2) {
return syms
}
// use peek
var res = [],
sum = null,
L = null,
R = null
for (var i = 0; i < syms.length; i++) {
var s = syms[i]
if (util.isSym(s, opArr)) {
if (sum == null) {
L = syms[i - 1]
sum = (util.isSym(L, [varArr[0]])) ? L : Ldef
}
R = syms[i + 1]
// if is var skip it since will be consumed
if (util.isSym(R, [varArr[1]])) { i++; }
// else reset to default
else { R = Rdef; }
// compute:
sum = execOp(sum, s, R)
// before loop quits due to possible i++, push the last
if (i == syms.length - 1) {
res.push(sum)
}
} else {
// s is not opArr, can't have been varArr either
// edge case: at first dont push
if (i > 0) {
res.push(sum)
res.push(s)
sum = null
}
}
}
return res
}
/**
* Execute non-commutative operation between 2 argument symbols and an op symbol; carry out respective ops according to symbol names.
* @param {symbol} L Left argument
* @param {symbol} op operation
* @param {symbol} R Right argument
* @param {str} offset The time origin offset
* @return {symbol} Result
*/
function execOp (L, op, R, offset) {
var otype = util.opType(L, op, R),
res = null
if (_.includes(['nn'], otype)) {
res = nnOp(L, op, R)
} else if (_.includes(['nT'], otype)) {
res = nTOp(L, op, R)
} else if (_.includes(['TT'], otype)) {
res = TTOp(L, op, R)
} else if (_.includes(['ToT', 'oT', 'To'], otype)) {
res = ToTOp(L, op, R, offset)
} else if (_.includes(['oo'], otype)) {
res = ooOp(L, R)
} else if (_.includes(['rT', 'TrT'], otype)) {
// has optional arg
res = rTOp(L, R)
} else if (_.includes(['cT', 'fcT', 'crT', 'fcrT'], otype)) {
// has optional arg
res = cTOp(L, R)
} else {
// not executable, e.g. not in the right order, return fully
res = (op == null) ? [L, R] : [L, op, R]
}
return res
}
/**
* Atomic binary arithmetic operation on the numerical level, with default overriding the argument prepended with '='.
* @param {string|Number} Lval The left argument value.
* @param {symbol} op The op symbol
* @param {string|Number} Rval The right argument value.
* @return {Number} Result from the operation.
*/
function atomicOp (Lval, op, Rval, dontOp) {
dontOp = dontOp || false
var oName = op.value
if (Lval == undefined) {
// if L is missing, R must exist tho
return (oName == 'minus') ? Rval.toString().replace(/(\d)/, '-$1') : Rval
} else if (Rval == undefined) {
// if L exists, be it def or not, R missing
return Lval
} else {
// or R exist or is default (parse to NaN), L can be default too but ignore then
var defL = Lval.toString().match(/^=/),
defR = Rval.toString().match(/^=/)
var l = parseFloat(Lval.toString().replace(/^=/, '')),
r = parseFloat(Rval.toString().replace(/^=/, ''))
if (defL && defR) {
// if both are default, return r 'last come last serve'
return r
} else if (defL && !defR) {
// if either default, return the non-default
return r
} else if (!defL && defR) {
return l
} else {
// none default
if (dontOp) {
// if is a don't operate together, i.e. for t, just return l
// 'first come first serve'
return l
} else {
// make the into proper floats first
if (oName == 'minus') {
return l - r
} else if (oName == 'plus') {
return l + r
} else if (oName == 'times') {
return l * r
} else if (oName == 'divide') {
return l / r
}
}
}
}
}
/**
* p#1: arithmetics: <n1>[<op>]<n2> ~ <n>, + if n1 > n2, * else
*/
function nnOp (L, op, R) {
var l = L.value,
r = R.value
// set the default op according to value in nn op
if (l > r) {
op = op || symbol('plus')
} else {
op = op || symbol('times')
}
var res = atomicOp(l, op, r)
return symbol(res)
}
/**
* p#2: redistribute, <n1><T1>[<op>]<n2><!T2> ~ <n1>[<op>]<n2> <T1>
* algorithm: note that from previous steps no <n>'s can occur adjacently
* 1. scan array L to R, on each <n> found:
* 2.1 if its R is <T>, continue
* 2.2 else, this is the target. do:
* 3.1 init carry = []. remove and push <n> into carry,
* 3.2 if its L is <op>, remove and prepend <op> into carry,
* 4.1 find the first <n> to the left, if not <n>, drop the carry and continue
* 4.2 else merge the carry after the <n>
* 5. At the end of loop, rerun production rule #1
*/
function nTnRedistribute (syms) {
if (syms.length < 2) {
return syms
}
// 1.
for (var i = 0; i < syms.length; i++) {
var s = syms[i]
if (util.sName(s) != 'n') {
continue
}
// 1.
var R = syms[i + 1]
if (util.sName(R) == 'T') {
continue
}
// 2.2
// 3.1 prepare the carry
var carry = []
// 3.2 the Left symbol
var L = syms[i - 1],
Li = -1
if (util.sName(L) == 'op') {
// if L is an 'op', remember to pull it later
Li = i - 1
}
// 4.1
// find L...L of L that is 'n'
var LLi = _.findLastIndex(syms.slice(0, i - 1), function (Ls) {
return util.sName(Ls) == 'n'
})
if (!syms[LLi] || util.sName(syms[LLi + 1]) != 'T') {
// if can't find 'n' (index = -1), or the R of 'n' isn't T, abort mission
// syms.splice(i, 0, carry)
} else {
// 4.2
// else, pull s at [i], optional L at [Li], and push at LLi+1
carry.push(_.pullAt(syms, i)[0])
if (Li != -1) {
carry.unshift(_.pullAt(syms, Li)[0])
}
syms.splice(LLi + 1, 0, carry)
syms = _.flatten(syms)
}
}
// 5. redo the <n><n> op
syms = reduce(syms, ['n', 'n'])
return syms
}
/**
* p#3: <n>[<op>]<T> ~ <T>, * if dt, + if t
* 1. if t can be overidden, start from the highest unit set to n, then return.
* 2. otherwise, if <dt> not empty, <n><dt> = <n>*<dt>, then return
* 3. else, if <t> not empty, <n><t> = <n>+<t>, then return
*/
function nTOp (nL, op, TR) {
var tOverrideUnit = util.highestOverride(TR.t)
if (tOverrideUnit) {
// 1.
TR.t[tOverrideUnit] = nL.value
} else if (_.keys(TR.dt).length) {
// 2.
op = op || symbol('times')
for (var k in TR.dt) {
if (k == 'wd') {
continue
}
TR.dt[k] = atomicOp(nL.value, op, TR.dt[k])
}
} else if (_.keys(TR.t).length) {
// 3.
op = op || symbol('plus')
for (var k in TR.t) {
TR.t[k] = atomicOp(nL.value, op, TR.t[k])
}
}
return TR
}
/**
* p#4: <T>[<op>]<T> ~ <T>
*/
function TTOp (TL, op, TR) {
// set the default op
op = op || symbol('plus')
// util.sName
// mutate into TL
for (var k in TR.t) {
// okay done add absolute time, just as you don't add origins together put u take gradual specificity, the 'true' param for dontOp if exist, return r
// override default tho, taken care of by atomic
TL.t[k] = atomicOp(TL.t[k], op, TR.t[k], true)
}
for (var k in TR.dt) {
if (k == 'wd') {
continue
}
TL.dt[k] = atomicOp(TL.dt[k], op, TR.dt[k])
}
return TL
}
/**
* p#5: defaulter <o> <n> <o> ~ <o> <T> <o>, d defaults to t:h
*/
function nDefTSyms (syms) {
var res = []
for (var i = 0; i < syms.length; i++) {
var s = syms[i]
res.push(util.isSym(s, ['n']) ? nDefT(s) : s)
}
return res
}
/**
* Helper: default a singlet n to T, i.e. next available hour
*/
function nDefT (n) {
var deft = symbol('t:1h,dt:')
var nVal = n.value
var currentHour = new Date().getHours()
var nextnVal = Math.floor(currentHour / 12) * 12 + nVal
var tHour = execOp(symbol(nextnVal), symbol('times'), deft)
return tHour
}
/**
* <o><o> ~ <o>*<o>
* To handle 'before next' etc.
*/
function ooOp (L, R) {
var Lsign = (L.value == 'plus') ? +1 : -1,
Rsign = (R.value == 'plus') ? +1 : -1,
LRsign = Lsign * Rsign
return (LRsign > 0) ? symbol('after') : symbol('before')
}
/**
* Next available T', given an offset, by incrementing in dt the next unit ++1 from the current largest unit in t.
*/
function nextAvailable (T, offset) {
// find the current largest and next largest unit
var nextUnit = util.nextLargestUnit(T)
// first finalized T
var finT1 = finalizeT([T], offset)[0],
stdStr1 = util.TtoStdT(finT1),
UTC1 = Date.parse(stdStr1),
UTCnow = Date.parse(new Date()),
UTCdiff = UTC1 - UTCnow
// if UTC1 is not in the future, add next unit
if (UTCdiff < 0) {
T.dt[nextUnit] = (T.dt[nextUnit] || 0) + 1
var finT2 = finalizeT([T], offset)[0]
return finT2
} else {
return finT1
}
}