-
Notifications
You must be signed in to change notification settings - Fork 0
/
evtData.js
458 lines (451 loc) · 16.6 KB
/
evtData.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
/*
* # evtData.js
* Author: [Sigfried Gold](http://sigfried.org)
* License: [MIT](http://sigfried.mit-license.org/)
*/
'use strict';
if (typeof require !== "undefined") {
var _ = require('supergroup');
var moment = require('moment');
}
var evtData = function() {
/** @namespace evtData */
// public
var entityIdProp
, eventNameProp
, startDateProp
, unitSettings = {unit: 'ms'}
, dateFormat = "M/D/YYYY"
, eventOrder
, filterFunc = function() { return true } // not used
;
// private
/*
origData: array of raw event objects, each expected to have an
entityId, and eventName, and a start date string
timelineArray: origData grouped by entityId. each entity has a records
array pointing to its raw event records and each of
those should have a pointer back to the timeline and
should be sorted in time order and should have
nextEvt/prevEvt pointers as appropriate
*/
function edata() {
};
function toDate(dateStr, fmt) { // storing dates as moment.js objects, at least for now
return moment(dateStr, fmt);
}
function sortEvts(list) {
return list.sort(function (a, b) {
var cmp = a.dt() - b.dt();
if (cmp === 0) {
if (eventOrder) {
cmp = eventOrder.indexOf(a.eventName())
- eventOrder.indexOf(b.eventName())
}
}
return cmp;
})
}
function Evt(raw, id, dateFormat) {
_.extend(this, raw);
this.eId = id;
this._moment = toDate(this[startDateProp], dateFormat);
if (!this._moment.isValid())
fail('invalid date');
this._entityId = this[entityIdProp];
this._eventName = this[eventNameProp];
}
Evt.prototype.id = function() {
return [this.entityId(), this.eventName(), this.dt()].join('/');
}
Evt.prototype.dt = function() {
return this._moment;
//return this._startDate;
}
Evt.prototype.dtStr = function(unit) {
unit = this.unit(unit);
var fmt;
switch (unit) {
case 'year':
fmt = 'YYYY'; break; // need a way to specify other fmts
case 'month':
fmt = 'MMM YYYY'; break;
case 'day':
fmt = 'MM/DD/YYYY'; break;
case 'hour':
fmt = 'MM/DD/YYYY hh:mma'; break;
case 'minute':
fmt = 'MM/DD/YYYY hh:mm:sa'; break;
default:
fmt = 'MM/DD/YYYY hh:mm:SSSa'; break;
}
return this._moment.format(fmt);
}
Evt.prototype.eventName = function() {
return this._eventName;
}
Evt.prototype.entityId = function() {
return this._entityId;
}
Evt.prototype.next = function() {
return this.timeline().records[this.evtIdx() + 1];
}
Evt.prototype.prev = function() {
return this.timeline().records[this.evtIdx() - 1];
}
Evt.prototype.hasNext = function() {
return !! this.next();
};
Evt.prototype.hasPrev = function() {
return !! this.prev();
};
Evt.prototype.toNext = function(ifNoNext, unit) {
if (ifNoNext && isNaN(parseInt(ifNoNext))) {
fail('bad ifNoNext param: ' + ifNoNext);
}
return this.hasNext() ? this.timeTo(this.next(), unit) : ifNoNext;
};
Evt.prototype.fromPrev = function(ifNoPrev, unit) {
if (ifNoPrev && isNaN(parseInt(ifNoPrev))) {
fail('bad ifNoPrev param: ' + ifNoPrev);
}
return this.hasPrev() ? this.prev().timeTo(this, unit) : ifNoPrev;
};
Evt.prototype.startIdx = function(unit) {
return this.timeline().firstEvt().timeTo(this, unit);
};
Evt.prototype.timeTo = function(otherEvt, unit) {
return this.dur(otherEvt.dt() - this.dt(), unit);
};
Evt.prototype.timeFrom = function(otherEvt, unit) {
return - this.timeTo(otherEvt, unit);
};
Evt.prototype.timeline = function (_) {
if (!arguments.length) return this._timeline;
this._timeline = _;
return this;
};
Evt.prototype.evtIdx = function (_) {
if (!arguments.length) return this._evtIdx;
this._evtIdx = _;
return this;
};
function Timeline(tl) { }
function makeTimeline(supergroupVal) {
var timeline = _.extend(supergroupVal, Timeline.prototype);
sortEvts(timeline.records);
timeline._evtLookup = {};
_.each(timeline.records, function (evt, i) {
evt.timeline(timeline); // give each evt a ref to the timeline it's in
evt.evtIdx(i); // tell each evt what position it has in the timeline
if (!_(timeline._evtLookup).has(evt.eventName())) {
timeline._evtLookup[evt.eventName()] = [i];
} else {
timeline._evtLookup[evt.eventName()].push(i);
}
})
return timeline;
}
Timeline.prototype.evtLookup = function(evtName, which) { // not being called at all right now?
console.log('FIX DUP PROBLEM!!!'); // just fixed, but not tested yet
if (_(this._evtLookup).has(evtName)) {
if (typeof(which) === "undefined") {
return this.records[this._evtLookup[which]]; // return evt at idx 0
}
if (!isNaN(which)) {
return this.records[this._evtLookup[which]]; // return evt at idx which
}
if (which === "all") {
return this.records[this._evtLookup[evtName]]; // return array
}
fail("you didn't say which and there's more than one");
}
// if evtName isn't in the timeline at all, return undefined
};
Timeline.prototype.firstEvt = function() {
return this.records[0];
};
Timeline.prototype.lastEvt = function() {
return this.records[this.records.length - 1];
};
Timeline.prototype.startDate = function() {
return this.firstEvt().dt();
};
Timeline.prototype.endDate = function() {
return this.lastEvt().dt();
return this.records[this.records.length - 1].dt();
};
Timeline.prototype.duration = function(unit) {
return this.firstEvt().timeTo(this.lastEvt(), unit);
};
Timeline.prototype.timelines = function (_) {
if (!arguments.length) return this._timelines;
this._timelines = _;
return this;
};
// @method whatAmI
// @returns Timeline constructor
// since timelines are String or Number objects (to represent their entityId)
// and I don't have a great way to subclass native types, this is a
// little kind of class test
Timeline.prototype.whatAmI = function () {
return Timeline.prototype;
};
function Timelines() { }
var makeTimelines = function(data) { // have some old code using this
var evts = _.chain(data)
.map(function(d,i) { return new Evt(d,i, dateFormat); })
.value();
var timelines = _.supergroup(evts, entityIdProp);
timelines = timelines
.map(function(d,i) {
return makeTimeline(d);
});
timelines._evtData = evts;
_.extend(timelines, Timelines.prototype);
_.each(timelines, function(timeline) {
timeline.timelines(timelines);
});
timelines._unitSettingsStack = [];
timelines.timelineUnit(true); // make sure they get set with all timelines in place
timelines.universeUnit(true);
return timelines;
}
Timelines.prototype.maxDuration = function (unit, recalc) {
if (typeof this._maxDuration === "undefined" || recalc)
// this .mox() is one of the places where
// underscore-unchained will bite you. moment.js doesn't
// like Number objects
this._maxDuration = _.chain(this).invoke('duration', 'justNumber').max().value();
return this.dur(this._maxDuration, unit);
}
Timelines.prototype.wholeSetDuration = function (unit, recalc) {
if (typeof this._setDuration === "undefined" || recalc)
this._setDuration = this.dur(
_.chain(this).invoke('startDate').max().value() -
_.chain(this).invoke('endDate').min().value(), 'justNumber');
return this.dur(this._setDuration, unit);
};
/*
* @method Timelines.universeUnit
* @param {string or boolean} [arg] falsy to get current val; String
* to set new val; true to recalculate
* @returns current val or object of method
*/
Timelines.prototype.universeUnit = function (arg) {
if (_.isString(arg)) {
this._universeUnit = arg;
return this;
}
if (typeof this._universeUnit === "undefined" || arg)
this._universeUnit = edata.durationUnits(
this.wholeSetDuration(null, arg));
return this._universeUnit;
};
Timelines.prototype.timelineUnit = function (arg) {
if (_.isString(arg)) {
this._timelineUnit = arg;
return this;
}
if (typeof this._timelineUnit === "undefined" || arg)
this._timelineUnit = edata.durationUnits(
this.maxDuration(null, arg));
return this._timelineUnit;
};
Timelines.prototype.unit = function(unit) {
if (unit === "universe")
return this.universeUnit();
if (unit === "timeline")
return this.timelineUnit();
if (typeof unit === "string")
return unit;
var u = this.unitSettings().unit;
if (u === "universe")
return this.universeUnit();
if (u === "timeline")
return this.timelineUnit();
return u;
};
Evt.prototype.unit = function(unit) { return this.timeline().unit(unit) };
Timeline.prototype.unit = function(unit) { return this.timelines().unit(unit) };
// @method unitSettings
// @param {Object} [opts]
// @param {boolean} [opts.unit] set default units, otherwise defaults to what edata has, which defaults to ms
// @param {boolean} [opts.withUnit] whether to attach unit string to reported durations
// @param {boolean} [opts.round] whether to round reported durations
// if used as a getter, returns unitSettings object
// if used as setter, returns 'this' (standard pattern to facilitate chaining, though it doesn't seem necessary here)
// when setting, it pushes old settings on a stack so you can set things temporarily
// you only have to supply the settings you want to change from the current settings
Timelines.prototype.unitSettings = function (opts) {
if (typeof this._unitSettings === "undefined")
this._unitSettings = _.clone(edata.unitSettings());
if (!arguments.length || _.isEmpty(opts)) return this._unitSettings;
this._unitSettingsStack.push(_.clone(this._unitSettings));
_.extend(this._unitSettings, opts);
return this;
};
Evt.prototype.unitSettings = function(opts) { return this.timeline().unitSettings(opts) };
Timeline.prototype.unitSettings = function(opts) { return this.timelines().unitSettings(opts) };
Timelines.prototype.restoreUnitSettings = function () {
return this._unitSettings =
this._unitSettingsStack.pop() || edata.unitSettings();
};
Evt.prototype.restoreUnitSettings = function() { return this.timeline().restoreUnitSettings() };
Timeline.prototype.restoreUnitSettings = function() { return this.timelines().restoreUnitSettings() };
Timelines.prototype.dur = function(num, unit) {
var tempSettings;
if (unit === 'justNumber') {
tempSettings = {withUnit: false};
} else if (_.isString(unit)) {
tempSettings = {unit: unit};
} else {
tempSettings = unit;
}
var result;
if (! _.isEmpty(unit)) {
this.unitSettings(tempSettings);
result = this.formatDur(num);
this.restoreUnitSettings();
} else {
result = this.formatDur(num);
}
return result;
}
Evt.prototype.dur = function(num,unit) { return this.timeline().dur(num,unit) };
Timeline.prototype.dur = function(num,unit) {
return this.timelines().dur(num,unit)
};
// @method formatDur
// report durations according to current settings
// @param {number} num the duration to express in certain units
// @return {string or number}
Timelines.prototype.formatDur = function(num) {
var settings = this.unitSettings();
var unit = this.unit(settings.unit);
var dur = settings.dontConvert ?
moment.duration(num, unit) :
moment.duration(num);
var newNum = dur.as(unit);
var decimals = Number(settings.round) - 1;
if (settings.round) {
newNum = Math.round(newNum * Math.pow(10,decimals)) / Math.pow(10,decimals);
}
if (settings.withUnit) {
if (unit === 'ms')
unit = 'milisecond';
if (newNum !== 1)
unit = unit + 's';
return newNum + ' ' + unit;
}
return newNum;
};
moment.locale('relTime', {
relativeTime : {
future: "%s",
past: "%s",
s: "second",
m: "second",
mm: "minute",
h: "minute",
hh: "hour",
d: "hour",
dd: "day",
M: "day",
MM: "month",
y: "month",
yy: "year"
}
});
moment.locale('en');
edata.durationUnits = function(dur) {
var locale = moment.locale();
moment.locale('relTime');
var unit = moment.duration(dur).humanize();
moment.locale(locale);
return unit;
};
Timelines.prototype.data = function () {
return this._evtData;
};
Timelines.prototype.sort = function (func) {
console.warn('is this called?'); // not from lifeflow...will test when i get to it
return _.addSupergroupMethods(this.slice(0).sort(func));
};
Timelines.prototype.evtDurationSortFunc = function (func) {
return function(a,b) {
var arec = a.evtLookup(evtName);
var brec = b.evtLookup(evtName);
if (!arec && !brec) return 0;
if (!arec) return 1;
if (!brec) return -1;
var A = arec.toNext();
var B = brec.toNext();
A = isNaN(A) ? -Infinity : A;
B = isNaN(B) ? -Infinity : B;
return B - A;
if (B < A) return -1; // descending order
if (A < B) return 1;
if (A === B) return 0;
fail("what did I forget?")
}
};
Timelines.prototype.evtDurationSortFunc = function (evtName) {
return this.sort(this.evtDurationSortFunc(evtName));
};
// @method whatAmI
// @returns Timelines constructor
// since timelines are Arrays and I don't have a great way to
// subclass native types, this is a little kind of class test
Timelines.prototype.whatAmI = function () {
return Timelines.prototype;
};
edata.entityIdProp = function (_) {
if (!arguments.length) return entityIdProp;
entityIdProp = _;
return edata;
};
edata.eventNameProp = function (_) {
if (!arguments.length) return eventNameProp;
eventNameProp = _;
return edata;
};
edata.startDateProp = function (_) {
if (!arguments.length) return startDateProp;
startDateProp = _;
return edata;
};
edata.unitSettings = function (_) {
if (!arguments.length) return unitSettings;
unitSettings = _;
return edata;
};
edata.eventOrder = function (_) {
if (!arguments.length) return eventOrder;
eventOrder = _;
return edata;
};
edata.dateFormat = function (_) {
if (!arguments.length) return dateFormat;
dateFormat = _;
return edata;
};
edata.filterFunc = function (_) {
fail("not being used anymore, but keeping just in case");
if (!arguments.length) return filterFunc;
filterFunc = _;
return edata;
};
function log(o) { console.log(o) };
function fail(thing) {
throw new Error(thing);
}
edata.Evt = Evt;
edata.Timeline = Timeline;
edata.Timelines = Timelines;
edata.makeTimelines = makeTimelines;
return edata;
}
if (typeof module !== "undefined") {
module.exports = evtData;
}