-
Notifications
You must be signed in to change notification settings - Fork 2
/
namespace.js
478 lines (447 loc) · 14.4 KB
/
namespace.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
var PolymerD3 = {};
PolymerD3.utilities = {};
PolymerD3.utilities.merge = function(from, to) {
var me = this;
this[to].forEach(function(t) {
me.push(from, t);
});
};
PolymerD3.utilities.isEmptyObject = function(obj) {
return obj.constructor === Object && Object.keys(obj).length === 0;
};
// Creates and attaches a dom node inside specific container and executes a meathod inside it
PolymerD3.utilities.attachElement = function(elem, container, cb) {
var dynamicEl = document.createElement(elem);
var containerElem = this.querySelector(container);
if (containerElem) {
containerElem.appendChild(dynamicEl);
} else {
this.appendChild(dynamicEl);
}
if (cb && dynamicEl[cb]) {
var callBack = dynamicEl[cb];
callBack.call(dynamicEl);
}
return dynamicEl;
};
// Parses changed Object from Array, works with deep obeservers
// Assumes arr is the array
PolymerD3.utilities.parsePath = function(path, arr) {
var index = path.split('.');
if (index.length > 1) {
index = index[1].slice(1);
return arr[index];
}
};
PolymerD3.utilities._setProperty = function(arr, key) {
if (arguments.length < 1) {
return;
}
var newVal = arguments[1];
this[arr].forEach(function(elem) {
if (elem.input === key) {
for (var newKey in newVal) {
elem[newKey] = newVal[newKey];
}
}
});
};
PolymerD3.utilities._getProperty = function(arr, key) {
var result;
this[arr].forEach(function(elem) {
if (elem.input === key) {
result = elem;
}
});
return result;
};
// Utility to create event notifying dataMutation
// Can be removed
PolymerD3.utilities.dataMutationEvent = function(data) {
var params = {
bubbles: true,
cancelable: true,
detail: data
};
return new CustomEvent('dataMutated', params);
};
PolymerD3.utilities.dataMutationParam = function(path, data, callBack) {
return {
data: data,
path: path,
callback: callBack
};
};
PolymerD3.fileReader = function(name, numberIndexArray, dateIndexArray, dateParser, callback, header) {
let arryadata = [];
let me = this;
d3.text(name, (error, text) => {
d3.csv.parseRows(text, (aline, ind) => {
if (ind == 0 && header === true) {
arryadata.push(aline);
} else {
numberIndexArray.forEach(token => {
aline[token] = +aline[token];
});
dateIndexArray.forEach(token => {
let tmp = aline[token];
aline[token] = d3.time.format(dateParser).parse(aline[token]);
// d3.parse not parsing date properly for _area.csv
if (!aline[token]) {
aline[token] = new Date(tmp);
}
});
arryadata.push(aline);
}
});
// callback((header)? arryadata.splice(1):arryadata);
callback.call(me,arryadata);
});
};
PolymerD3.axis = function(type, bound, range) {
var map = {
'number': d3.scale.linear(),
'time': d3.time.scale(),
'currency': d3.scale.linear(),
'percent': d3.scale.linear(),
'category': d3.scale.ordinal()
};
var formaterMap = {
'time': {
'Tabbrweekday': '%a ',
'Tabbrmonth': '%b '
},
'category': '',
'number': '.2s',
'currency': '$.2s',
'percent': '.0%'
};
var scale = map[type];
var axis = d3.svg.axis();
if(range){
scale.range(range);
}
if (bound) {
scale.domain(bound);
if (d3.timeYear.count(bound[0], bound[1]) < 10) {
if (d3.timeMonth.count(bound[0], bound[1]) < 10) {
if (d3.timeWeek.count(bound[0], bound[1]) < 10) {
//todo
if (d3.timeDay.count(bound[0], bound[1]) < 10) {
if (d3.timeHour.count(bound[0], bound[1]) < 240) {
if (((d3.time.format('%H:%M')(bound[0])) === '00:00') && ((d3.time.format('%H:%M')(bound[1])) === '00:00')) {
axis.tickFormat(d3.time.format('%d-%b'));
} else{
axis.tickFormat(d3.time.format('%a-%I-%M'));
}
} else {
axis.tickFormat(d3.time.format('%d-%b'));
}
} else {
axis.tickFormat(d3.time.format('%d-%b'));
}
// axis.tickFormat(d3.time.format('%d-%b'));
}
} else {
axis.tickFormat(d3.time.format('%a-%b'));
}
} else {
axis.tickFormat(d3.time.format('%b-%Y'));
}
}
if (type === 'category')
axis.tickFormat(d3.format(formaterMap[type]));
axis.scale(scale);
return axis;
};
PolymerD3.setSvgArea = function(svg, width, height, margin){
svg.attr('width', width + margin.left + margin.right)
.attr('height', height + margin.top + margin.bottom)
//There is a small problem with this, some charts don't just append a <g> directly to <svg>
.append('g')
.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')');
return svg;
};
PolymerD3.utilities.getUUID = function() {
function s4() {
return Math.floor((1 + Math.random()) * 0x10000)
.toString(16)
.substring(1);
}
return s4() + s4() + '-' + s4() + '-' + s4() + '-' +
s4() + '-' + s4() + s4() + s4();
};
PolymerD3.utilities.clone = function(obj) {
var clone;
if (obj) {
clone = JSON.stringify(obj);
clone = JSON.parse(clone);
}
return clone;
};
PolymerD3.summarizeData = (data, xIndex, xFormat, yIndices, yFormat, stack, measure) => {
var Xdomain = [];
var Ydomain;
var stacked;
var xSet = d3.set();
var findMinMax = function() {
var whenNotOrdinal = function(){
var priYMin;
var priYMax;
var priXMin;
var priXMax;
data.forEach((aRow, i) => {
if(i == 0){
priYMax = priYMin = aRow[yIndices[0]];
priXMax = priXMin = aRow[xIndex];
}
else{
if(aRow[yIndices[0]] < priYMin){
priYMin = aRow[yIndices[0]] ;
}
if(aRow[yIndices[0]] > priYMax){
priYMax = aRow[yIndices[0]] ;
}
if(aRow[xIndex] < priXMin){
priXMin = aRow[xIndex] ;
}
if(aRow[xIndex] > priXMax){
priXMax = aRow[xIndex] ;
}
}
});
Xdomain= [priXMin, priXMax];
Ydomain= [priYMin, priYMax];
};
var whenOrdinal = function(){
var priYMin;
var priYMax;
var setX = d3.set();
data.forEach((aRow, i) => {
if(i == 0){
priYMax = priYMin = aRow[yIndices[0]];
setX.add(aRow[xIndex]);
}
else{
if(aRow[yIndices[0]] < priYMin){
priYMin = aRow[yIndices[0]] ;
}
if(aRow[yIndices[0]] > priYMax){
priYMax = aRow[yIndices[0]] ;
}
// Todo optimize
setX.add(aRow[xIndex]);
}
});
Xdomain= setX.values();
Ydomain= [priYMin, priYMax];
};
if(xFormat === 'ordinal'){
whenOrdinal();
}else{
whenNotOrdinal();
}
};
var findStackedMinMax = (data) => {
var layerArray = [];
var converter = (arg) => {
var convertDate = function(strDate){
return new Date(strDate);
};
var convertNum = function(num) {
return +num;
};
var convertStr = function(str) {
return str;
};
if (arg instanceof Date) {
return convertDate;
} else if (typeof arg === 'number') {
return convertNum;
} else {
return convertStr;
}
};
var convert = converter(data[0][xIndex]);
// group by key.
var layers = d3.nest()
.key(function(d) {
return d[xIndex];
})
.entries(data)
.map((d) => {
var r = [convert(d.key)];
d.values.forEach(v => {
r.push(v[yIndices[0]])
})
return r;
});
stackFromMultiColoumn(layers, [1, 2, 3], 0);
// stackFromMultiColoumn(layerArray, new params);
};
var stackFromMultiColoumn = (data, newYIndices, newXIndex) => {
var layers = [];
if (!newYIndices) {
newYIndices = yIndices;
}
if (newXIndex === undefined || newXIndex === null) {
newXIndex = xIndex;
}
if (xFormat === 'ordinal') {
// yIndices = [0,1,2,3];
newYIndices.forEach(function (aCatIndex) {
var catArray = [];
data.forEach(function (datum) {
catArray.push([datum[newXIndex], datum[aCatIndex]]);
// Todo: Optimize
});
layers.push(catArray);
});
stacked = d3.layout.stack().y((d)=>{return d[1]})(layers);
var topS = stacked[stacked.length-1];
Ydomain = d3.extent(topS, (d) => {return (d.y + d.y0)})
Xdomain = topS.map(t => {return t[newXIndex]})
} else {
newYIndices.forEach(function (aCatIndex) {
var catArray = [];
data.forEach(function (datum) {
catArray.push([datum[newXIndex], datum[aCatIndex]]);
});
layers.push(catArray);
});
stacked = d3.layout.stack().y((d)=>{return d[1]})(layers);
var topS = stacked[stacked.length-1];
Ydomain = d3.extent(topS, (d) => {return (d.y + d.y0)})
Xdomain = d3.extent(topS, (d) => {return d[0];} );
}
};
var groupFromMultiColoumn = (data) => {
Ymax = d3.max(data, function (aRow) {
return d3.max(aRow.filter(function (value, index) {
return yIndices.includes(index);
}));
});
Ymin = d3.min(data, function (aRow) {
return d3.min(aRow.filter(function (value, index) {
return yIndices.includes(index);
}));
});
if (xFormat === 'ordinal') {
data.forEach(function(datum) {
xSet.add(datum[xIndex]);
});
Xdomain = xSet.values();
} else {
Xmax = d3.max(data, function (aRow) {
return d3.max(aRow.filter(function (value, index) {
return index == xIndex;
}));
});
Xmin = d3.min(data, function (aRow) {
return d3.min(aRow.filter(function (value, index) {
return index == xIndex;
}));
});
Xdomain = [Xmin, Xmax];
}
Ydomain = [Ymin, Ymax];
}
if(yIndices.length == 1){
var handler = (stack) ? findStackedMinMax : findMinMax;
handler(data);
}
else if (yIndices.length > 1){
var handler = (stack) ? stackFromMultiColoumn : groupFromMultiColoumn;
handler(data);
}
else{
throw new Error("invalid entry in yIndices" + yIndices);
}
// findYDomain(dataSummary, yFormat);
console.log("xDom:" + Xdomain + " yDom:" + Ydomain);
return {
'getStack': ()=>{
return stacked;
},
'getXDomain': () => {
return Xdomain
},
'getYDomain': () => {
return Ydomain
}
};
};
PolymerD3.rollup = (data, groupby, handler) =>{
var dataSummary = d3.nest()
.key((d) => {
return d[groupby];
})
.rollup((aRow) => {
handler(aRow);
})
.entries(data);
return dataSummary;
};
PolymerD3.rollupMultiValued = (columns, columnHeaders, xId, data)=>{
var multiValue = columns.map(function(id) {
return {
id: columnHeaders[id],
values: data.map((d) => {
return {'x': d[xId], 'y': d[id]};
})
};
});
return multiValue;
};
PolymerD3.utilities.searchArr = function(arr, matchFn) {
return arr.reduce((accum, elem) => {
if (matchFn(elem)) {
return elem;
} else {
// just some FP craziness
// http://stackoverflow.com/a/30042948
// http://redux.js.org/docs/recipes/UsingObjectSpreadOperator.html
return Object.assign({}, accum);
}
}, {});;
}
// compares and merges arays
// example:
// a => [1, 2, 3]; b => [2, 3, 5];
// comparison() => (if b[i] not in a, return true);
// f(a, b, comparison) = [1, 2, 3, 5]
PolymerD3.utilities.compareAndMerge = function(from, to, comparison) {
let merged = to.reduce((accum, elem) => {
let _temp;
if (comparison(elem)){
_temp = [elem];
} else {
_temp = [];
}
// avoiding mutations with concat, slice and spreaf
// https://egghead.io/lessons/javascript-redux-avoiding-array-mutations-with-concat-slice-and-spread
return accum.concat(_temp);
}, []);
return from.concat(merged);
}
// 'mutates' the object statisying 'condition' in the array of a objects 'arr'
PolymerD3.utilities.mutateObjInArr = function(arr, condition, mutation) {
var newArr = arr.map(elem => {
if (condition(elem)) {
return mutation(elem);
}
return elem;
});
return newArr;
}
// https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Math/trunc
// polyfill for math.trunc
PolymerD3.utilities.truncateFloat = Math.trunc || function(x) {
if (isNaN(x)) {
return NaN;
}
if (x > 0) {
return Math.floor(x);
}
return Math.ceil(x);
};