forked from dc-js/dc.js
-
Notifications
You must be signed in to change notification settings - Fork 0
/
dc.js
13594 lines (12140 loc) · 450 KB
/
dc.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
/*!
* dc 3.0.12
* http://dc-js.github.io/dc.js/
* Copyright 2012-2019 Nick Zhu & the dc.js Developers
* https://github.com/dc-js/dc.js/blob/master/AUTHORS
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
(function() { function _dc(d3, crossfilter) {
'use strict';
/**
* The entire dc.js library is scoped under the **dc** name space. It does not introduce
* anything else into the global name space.
*
* Most `dc` functions are designed to allow function chaining, meaning they return the current chart
* instance whenever it is appropriate. The getter forms of functions do not participate in function
* chaining because they return values that are not the chart, although some,
* such as {@link dc.baseMixin#svg .svg} and {@link dc.coordinateGridMixin#xAxis .xAxis},
* return values that are themselves chainable d3 objects.
* @namespace dc
* @version 3.0.12
* @example
* // Example chaining
* chart.width(300)
* .height(300)
* .filter('sunday');
*/
/*jshint -W079*/
var dc = {
version: '3.0.12',
constants: {
CHART_CLASS: 'dc-chart',
DEBUG_GROUP_CLASS: 'debug',
STACK_CLASS: 'stack',
DESELECTED_CLASS: 'deselected',
SELECTED_CLASS: 'selected',
NODE_INDEX_NAME: '__index__',
GROUP_INDEX_NAME: '__group_index__',
DEFAULT_CHART_GROUP: '__default_chart_group__',
EVENT_DELAY: 40,
NEGLIGIBLE_NUMBER: 1e-10
},
_renderlet: null
};
/*jshint +W079*/
/**
* The dc.chartRegistry object maintains sets of all instantiated dc.js charts under named groups
* and the default group.
*
* A chart group often corresponds to a crossfilter instance. It specifies
* the set of charts which should be updated when a filter changes on one of the charts or when the
* global functions {@link dc.filterAll dc.filterAll}, {@link dc.refocusAll dc.refocusAll},
* {@link dc.renderAll dc.renderAll}, {@link dc.redrawAll dc.redrawAll}, or chart functions
* {@link dc.baseMixin#renderGroup baseMixin.renderGroup},
* {@link dc.baseMixin#redrawGroup baseMixin.redrawGroup} are called.
*
* @namespace chartRegistry
* @memberof dc
* @type {{has, register, deregister, clear, list}}
*/
dc.chartRegistry = (function () {
// chartGroup:string => charts:array
var _chartMap = {};
function initializeChartGroup (group) {
if (!group) {
group = dc.constants.DEFAULT_CHART_GROUP;
}
if (!_chartMap[group]) {
_chartMap[group] = [];
}
return group;
}
return {
/**
* Determine if a given chart instance resides in any group in the registry.
* @method has
* @memberof dc.chartRegistry
* @param {Object} chart dc.js chart instance
* @returns {Boolean}
*/
has: function (chart) {
for (var e in _chartMap) {
if (_chartMap[e].indexOf(chart) >= 0) {
return true;
}
}
return false;
},
/**
* Add given chart instance to the given group, creating the group if necessary.
* If no group is provided, the default group `dc.constants.DEFAULT_CHART_GROUP` will be used.
* @method register
* @memberof dc.chartRegistry
* @param {Object} chart dc.js chart instance
* @param {String} [group] Group name
*/
register: function (chart, group) {
group = initializeChartGroup(group);
_chartMap[group].push(chart);
},
/**
* Remove given chart instance from the given group, creating the group if necessary.
* If no group is provided, the default group `dc.constants.DEFAULT_CHART_GROUP` will be used.
* @method deregister
* @memberof dc.chartRegistry
* @param {Object} chart dc.js chart instance
* @param {String} [group] Group name
*/
deregister: function (chart, group) {
group = initializeChartGroup(group);
for (var i = 0; i < _chartMap[group].length; i++) {
if (_chartMap[group][i].anchorName() === chart.anchorName()) {
_chartMap[group].splice(i, 1);
break;
}
}
},
/**
* Clear given group if one is provided, otherwise clears all groups.
* @method clear
* @memberof dc.chartRegistry
* @param {String} group Group name
*/
clear: function (group) {
if (group) {
delete _chartMap[group];
} else {
_chartMap = {};
}
},
/**
* Get an array of each chart instance in the given group.
* If no group is provided, the charts in the default group are returned.
* @method list
* @memberof dc.chartRegistry
* @param {String} [group] Group name
* @returns {Array<Object>}
*/
list: function (group) {
group = initializeChartGroup(group);
return _chartMap[group];
}
};
})();
/**
* Add given chart instance to the given group, creating the group if necessary.
* If no group is provided, the default group `dc.constants.DEFAULT_CHART_GROUP` will be used.
* @memberof dc
* @method registerChart
* @param {Object} chart dc.js chart instance
* @param {String} [group] Group name
*/
dc.registerChart = function (chart, group) {
dc.chartRegistry.register(chart, group);
};
/**
* Remove given chart instance from the given group, creating the group if necessary.
* If no group is provided, the default group `dc.constants.DEFAULT_CHART_GROUP` will be used.
* @memberof dc
* @method deregisterChart
* @param {Object} chart dc.js chart instance
* @param {String} [group] Group name
*/
dc.deregisterChart = function (chart, group) {
dc.chartRegistry.deregister(chart, group);
};
/**
* Determine if a given chart instance resides in any group in the registry.
* @memberof dc
* @method hasChart
* @param {Object} chart dc.js chart instance
* @returns {Boolean}
*/
dc.hasChart = function (chart) {
return dc.chartRegistry.has(chart);
};
/**
* Clear given group if one is provided, otherwise clears all groups.
* @memberof dc
* @method deregisterAllCharts
* @param {String} group Group name
*/
dc.deregisterAllCharts = function (group) {
dc.chartRegistry.clear(group);
};
/**
* Clear all filters on all charts within the given chart group. If the chart group is not given then
* only charts that belong to the default chart group will be reset.
* @memberof dc
* @method filterAll
* @param {String} [group]
*/
dc.filterAll = function (group) {
var charts = dc.chartRegistry.list(group);
for (var i = 0; i < charts.length; ++i) {
charts[i].filterAll();
}
};
/**
* Reset zoom level / focus on all charts that belong to the given chart group. If the chart group is
* not given then only charts that belong to the default chart group will be reset.
* @memberof dc
* @method refocusAll
* @param {String} [group]
*/
dc.refocusAll = function (group) {
var charts = dc.chartRegistry.list(group);
for (var i = 0; i < charts.length; ++i) {
if (charts[i].focus) {
charts[i].focus();
}
}
};
/**
* Re-render all charts belong to the given chart group. If the chart group is not given then only
* charts that belong to the default chart group will be re-rendered.
* @memberof dc
* @method renderAll
* @param {String} [group]
*/
dc.renderAll = function (group) {
var charts = dc.chartRegistry.list(group);
for (var i = 0; i < charts.length; ++i) {
charts[i].render();
}
if (dc._renderlet !== null) {
dc._renderlet(group);
}
};
/**
* Redraw all charts belong to the given chart group. If the chart group is not given then only charts
* that belong to the default chart group will be re-drawn. Redraw is different from re-render since
* when redrawing dc tries to update the graphic incrementally, using transitions, instead of starting
* from scratch.
* @memberof dc
* @method redrawAll
* @param {String} [group]
*/
dc.redrawAll = function (group) {
var charts = dc.chartRegistry.list(group);
for (var i = 0; i < charts.length; ++i) {
charts[i].redraw();
}
if (dc._renderlet !== null) {
dc._renderlet(group);
}
};
/**
* If this boolean is set truthy, all transitions will be disabled, and changes to the charts will happen
* immediately.
* @memberof dc
* @member disableTransitions
* @type {Boolean}
* @default false
*/
dc.disableTransitions = false;
/**
* Start a transition on a selection if transitions are globally enabled
* ({@link dc.disableTransitions} is false) and the duration is greater than zero; otherwise return
* the selection. Since most operations are the same on a d3 selection and a d3 transition, this
* allows a common code path for both cases.
* @memberof dc
* @method transition
* @param {d3.selection} selection - the selection to be transitioned
* @param {Number|Function} [duration=250] - the duration of the transition in milliseconds, a
* function returning the duration, or 0 for no transition
* @param {Number|Function} [delay] - the delay of the transition in milliseconds, or a function
* returning the delay, or 0 for no delay
* @param {String} [name] - the name of the transition (if concurrent transitions on the same
* elements are needed)
* @returns {d3.transition|d3.selection}
*/
dc.transition = function (selection, duration, delay, name) {
if (dc.disableTransitions || duration <= 0) {
return selection;
}
var s = selection.transition(name);
if (duration >= 0 || duration !== undefined) {
s = s.duration(duration);
}
if (delay >= 0 || delay !== undefined) {
s = s.delay(delay);
}
return s;
};
/* somewhat silly, but to avoid duplicating logic */
dc.optionalTransition = function (enable, duration, delay, name) {
if (enable) {
return function (selection) {
return dc.transition(selection, duration, delay, name);
};
} else {
return function (selection) {
return selection;
};
}
};
// See http://stackoverflow.com/a/20773846
dc.afterTransition = function (transition, callback) {
if (transition.empty() || !transition.duration) {
callback.call(transition);
} else {
var n = 0;
transition
.each(function () { ++n; })
.on('end', function () {
if (!--n) {
callback.call(transition);
}
});
}
};
/**
* @namespace units
* @memberof dc
* @type {{}}
*/
dc.units = {};
/**
* The default value for {@link dc.coordinateGridMixin#xUnits .xUnits} for the
* {@link dc.coordinateGridMixin Coordinate Grid Chart} and should
* be used when the x values are a sequence of integers.
* It is a function that counts the number of integers in the range supplied in its start and end parameters.
* @method integers
* @memberof dc.units
* @see {@link dc.coordinateGridMixin#xUnits coordinateGridMixin.xUnits}
* @example
* chart.xUnits(dc.units.integers) // already the default
* @param {Number} start
* @param {Number} end
* @returns {Number}
*/
dc.units.integers = function (start, end) {
return Math.abs(end - start);
};
/**
* This argument can be passed to the {@link dc.coordinateGridMixin#xUnits .xUnits} function of a
* coordinate grid chart to specify ordinal units for the x axis. Usually this parameter is used in
* combination with passing
* {@link https://github.com/d3/d3-scale/blob/master/README.md#ordinal-scales d3.scaleOrdinal}
* to {@link dc.coordinateGridMixin#x .x}.
*
* As of dc.js 3.0, this is purely a placeholder or magic value which causes the chart to go into ordinal mode; the
* function is not called.
* @method ordinal
* @memberof dc.units
* @see {@link https://github.com/d3/d3-scale/blob/master/README.md#ordinal-scales d3.scaleOrdinal}
* @see {@link dc.coordinateGridMixin#xUnits coordinateGridMixin.xUnits}
* @see {@link dc.coordinateGridMixin#x coordinateGridMixin.x}
* @example
* chart.xUnits(dc.units.ordinal)
* .x(d3.scaleOrdinal())
*/
dc.units.ordinal = function () {
throw new Error('dc.units.ordinal should not be called - it is a placeholder');
};
/**
* @namespace fp
* @memberof dc.units
* @type {{}}
*/
dc.units.fp = {};
/**
* This function generates an argument for the {@link dc.coordinateGridMixin Coordinate Grid Chart}
* {@link dc.coordinateGridMixin#xUnits .xUnits} function specifying that the x values are floating-point
* numbers with the given precision.
* The returned function determines how many values at the given precision will fit into the range
* supplied in its start and end parameters.
* @method precision
* @memberof dc.units.fp
* @see {@link dc.coordinateGridMixin#xUnits coordinateGridMixin.xUnits}
* @example
* // specify values (and ticks) every 0.1 units
* chart.xUnits(dc.units.fp.precision(0.1)
* // there are 500 units between 0.5 and 1 if the precision is 0.001
* var thousandths = dc.units.fp.precision(0.001);
* thousandths(0.5, 1.0) // returns 500
* @param {Number} precision
* @returns {Function} start-end unit function
*/
dc.units.fp.precision = function (precision) {
var _f = function (s, e) {
var d = Math.abs((e - s) / _f.resolution);
if (dc.utils.isNegligible(d - Math.floor(d))) {
return Math.floor(d);
} else {
return Math.ceil(d);
}
};
_f.resolution = precision;
return _f;
};
dc.round = {};
dc.round.floor = function (n) {
return Math.floor(n);
};
dc.round.ceil = function (n) {
return Math.ceil(n);
};
dc.round.round = function (n) {
return Math.round(n);
};
dc.override = function (obj, functionName, newFunction) {
var existingFunction = obj[functionName];
obj['_' + functionName] = existingFunction;
obj[functionName] = newFunction;
};
dc.renderlet = function (_) {
if (!arguments.length) {
return dc._renderlet;
}
dc._renderlet = _;
return dc;
};
dc.instanceOfChart = function (o) {
return o instanceof Object && o.__dcFlag__ && true;
};
// polyfill for IE
// from https://developer.mozilla.org/en-US/docs/Web/API/Element/matches#Polyfill
if (!Element.prototype.matches) {
Element.prototype.matches =
Element.prototype.matchesSelector ||
Element.prototype.mozMatchesSelector ||
Element.prototype.msMatchesSelector ||
Element.prototype.oMatchesSelector ||
Element.prototype.webkitMatchesSelector ||
function (s) {
var matches = (this.document || this.ownerDocument).querySelectorAll(s),
i = matches.length;
do {
--i;
}
while (i >= 0 && matches.item(i) !== this);
return i > -1;
};
}
dc.errors = {};
dc.errors.Exception = function (msg) {
var _msg = msg || 'Unexpected internal error';
this.message = _msg;
this.toString = function () {
return _msg;
};
this.stack = (new Error()).stack;
};
dc.errors.Exception.prototype = Object.create(Error.prototype);
dc.errors.Exception.prototype.constructor = dc.errors.Exception;
dc.errors.InvalidStateException = function () {
dc.errors.Exception.apply(this, arguments);
};
dc.errors.InvalidStateException.prototype = Object.create(dc.errors.Exception.prototype);
dc.errors.InvalidStateException.prototype.constructor = dc.errors.InvalidStateException;
dc.errors.BadArgumentException = function () {
dc.errors.Exception.apply(this, arguments);
};
dc.errors.BadArgumentException.prototype = Object.create(dc.errors.Exception.prototype);
dc.errors.BadArgumentException.prototype.constructor = dc.errors.BadArgumentException;
/**
* The default date format for dc.js
* @name dateFormat
* @memberof dc
* @type {Function}
* @default d3.timeFormat('%m/%d/%Y')
*/
dc.dateFormat = d3.timeFormat('%m/%d/%Y');
/**
* @namespace printers
* @memberof dc
* @type {{}}
*/
dc.printers = {};
/**
* Converts a list of filters into a readable string.
* @method filters
* @memberof dc.printers
* @param {Array<dc.filters>} filters
* @returns {String}
*/
dc.printers.filters = function (filters) {
var s = '';
for (var i = 0; i < filters.length; ++i) {
if (i > 0) {
s += ', ';
}
s += dc.printers.filter(filters[i]);
}
return s;
};
/**
* Converts a filter into a readable string.
* @method filter
* @memberof dc.printers
* @param {dc.filters|any|Array<any>} filter
* @returns {String}
*/
dc.printers.filter = function (filter) {
var s = '';
if (typeof filter !== 'undefined' && filter !== null) {
if (filter instanceof Array) {
if (filter.length >= 2) {
s = '[' + filter.map(function (e) {
return dc.utils.printSingleValue(e);
}).join(' -> ') + ']';
} else if (filter.length >= 1) {
s = dc.utils.printSingleValue(filter[0]);
}
} else {
s = dc.utils.printSingleValue(filter);
}
}
return s;
};
/**
* Returns a function that given a string property name, can be used to pluck the property off an object. A function
* can be passed as the second argument to also alter the data being returned.
*
* This can be a useful shorthand method to create accessor functions.
* @method pluck
* @memberof dc
* @example
* var xPluck = dc.pluck('x');
* var objA = {x: 1};
* xPluck(objA) // 1
* @example
* var xPosition = dc.pluck('x', function (x, i) {
* // `this` is the original datum,
* // `x` is the x property of the datum,
* // `i` is the position in the array
* return this.radius + x;
* });
* dc.selectAll('.circle').data(...).x(xPosition);
* @param {String} n
* @param {Function} [f]
* @returns {Function}
*/
dc.pluck = function (n, f) {
if (!f) {
return function (d) { return d[n]; };
}
return function (d, i) { return f.call(d, d[n], i); };
};
/**
* @namespace utils
* @memberof dc
* @type {{}}
*/
dc.utils = {};
/**
* Print a single value filter.
* @method printSingleValue
* @memberof dc.utils
* @param {any} filter
* @returns {String}
*/
dc.utils.printSingleValue = function (filter) {
var s = '' + filter;
if (filter instanceof Date) {
s = dc.dateFormat(filter);
} else if (typeof(filter) === 'string') {
s = filter;
} else if (dc.utils.isFloat(filter)) {
s = dc.utils.printSingleValue.fformat(filter);
} else if (dc.utils.isInteger(filter)) {
s = Math.round(filter);
}
return s;
};
dc.utils.printSingleValue.fformat = d3.format('.2f');
// convert 'day' to 'timeDay' and similar
dc.utils.toTimeFunc = function (t) {
return 'time' + t.charAt(0).toUpperCase() + t.slice(1);
};
/**
* Arbitrary add one value to another.
*
* If the value l is of type Date, adds r units to it. t becomes the unit.
* For example dc.utils.add(dt, 3, 'week') will add 3 (r = 3) weeks (t= 'week') to dt.
*
* If l is of type numeric, t is ignored. In this case if r is of type string,
* it is assumed to be percentage (whether or not it includes %). For example
* dc.utils.add(30, 10) will give 40 and dc.utils.add(30, '10') will give 33.
*
* They also generate strange results if l is a string.
* @method add
* @memberof dc.utils
* @param {Date|Number} l the value to modify
* @param {String|Number} r the amount by which to modify the value
* @param {Function|String} [t=d3.timeDay] if `l` is a `Date`, then this should be a
* [d3 time interval](https://github.com/d3/d3-time/blob/master/README.md#_interval).
* For backward compatibility with dc.js 2.0, it can also be the name of an interval, i.e.
* 'millis', 'second', 'minute', 'hour', 'day', 'week', 'month', or 'year'
* @returns {Date|Number}
*/
dc.utils.add = function (l, r, t) {
if (typeof r === 'string') {
r = r.replace('%', '');
}
if (l instanceof Date) {
if (typeof r === 'string') {
r = +r;
}
if (t === 'millis') {
return new Date(l.getTime() + r);
}
t = t || d3.timeDay;
if (typeof t !== 'function') {
t = d3[dc.utils.toTimeFunc(t)];
}
return t.offset(l, r);
} else if (typeof r === 'string') {
var percentage = (+r / 100);
return l > 0 ? l * (1 + percentage) : l * (1 - percentage);
} else {
return l + r;
}
};
/**
* Arbitrary subtract one value from another.
*
* If the value l is of type Date, subtracts r units from it. t becomes the unit.
* For example dc.utils.subtract(dt, 3, 'week') will subtract 3 (r = 3) weeks (t= 'week') from dt.
*
* If l is of type numeric, t is ignored. In this case if r is of type string,
* it is assumed to be percentage (whether or not it includes %). For example
* dc.utils.subtract(30, 10) will give 20 and dc.utils.subtract(30, '10') will give 27.
*
* They also generate strange results if l is a string.
* @method subtract
* @memberof dc.utils
* @param {Date|Number} l the value to modify
* @param {String|Number} r the amount by which to modify the value
* @param {Function|String} [t=d3.timeDay] if `l` is a `Date`, then this should be a
* [d3 time interval](https://github.com/d3/d3-time/blob/master/README.md#_interval).
* For backward compatibility with dc.js 2.0, it can also be the name of an interval, i.e.
* 'millis', 'second', 'minute', 'hour', 'day', 'week', 'month', or 'year'
* @returns {Date|Number}
*/
dc.utils.subtract = function (l, r, t) {
if (typeof r === 'string') {
r = r.replace('%', '');
}
if (l instanceof Date) {
if (typeof r === 'string') {
r = +r;
}
if (t === 'millis') {
return new Date(l.getTime() - r);
}
t = t || d3.timeDay;
if (typeof t !== 'function') {
t = d3[dc.utils.toTimeFunc(t)];
}
return t.offset(l, -r);
} else if (typeof r === 'string') {
var percentage = (+r / 100);
return l < 0 ? l * (1 + percentage) : l * (1 - percentage);
} else {
return l - r;
}
};
/**
* Is the value a number?
* @method isNumber
* @memberof dc.utils
* @param {any} n
* @returns {Boolean}
*/
dc.utils.isNumber = function (n) {
return n === +n;
};
/**
* Is the value a float?
* @method isFloat
* @memberof dc.utils
* @param {any} n
* @returns {Boolean}
*/
dc.utils.isFloat = function (n) {
return n === +n && n !== (n | 0);
};
/**
* Is the value an integer?
* @method isInteger
* @memberof dc.utils
* @param {any} n
* @returns {Boolean}
*/
dc.utils.isInteger = function (n) {
return n === +n && n === (n | 0);
};
/**
* Is the value very close to zero?
* @method isNegligible
* @memberof dc.utils
* @param {any} n
* @returns {Boolean}
*/
dc.utils.isNegligible = function (n) {
return !dc.utils.isNumber(n) || (n < dc.constants.NEGLIGIBLE_NUMBER && n > -dc.constants.NEGLIGIBLE_NUMBER);
};
/**
* Ensure the value is no greater or less than the min/max values. If it is return the boundary value.
* @method clamp
* @memberof dc.utils
* @param {any} val
* @param {any} min
* @param {any} max
* @returns {any}
*/
dc.utils.clamp = function (val, min, max) {
return val < min ? min : (val > max ? max : val);
};
/**
* Given `x`, return a function that always returns `x`.
*
* {@link https://github.com/d3/d3/blob/master/CHANGES.md#internals `d3.functor` was removed in d3 version 4}.
* This function helps to implement the replacement,
* `typeof x === "function" ? x : dc.utils.constant(x)`
* @method constant
* @memberof dc.utils
* @param {any} x
* @returns {Function}
*/
dc.utils.constant = function (x) {
return function () {
return x;
};
};
/**
* Using a simple static counter, provide a unique integer id.
* @method uniqueId
* @memberof dc.utils
* @returns {Number}
*/
var _idCounter = 0;
dc.utils.uniqueId = function () {
return ++_idCounter;
};
/**
* Convert a name to an ID.
* @method nameToId
* @memberof dc.utils
* @param {String} name
* @returns {String}
*/
dc.utils.nameToId = function (name) {
return name.toLowerCase().replace(/[\s]/g, '_').replace(/[\.']/g, '');
};
/**
* Append or select an item on a parent element.
* @method appendOrSelect
* @memberof dc.utils
* @param {d3.selection} parent
* @param {String} selector
* @param {String} tag
* @returns {d3.selection}
*/
dc.utils.appendOrSelect = function (parent, selector, tag) {
tag = tag || selector;
var element = parent.select(selector);
if (element.empty()) {
element = parent.append(tag);
}
return element;
};
/**
* Return the number if the value is a number; else 0.
* @method safeNumber
* @memberof dc.utils
* @param {Number|any} n
* @returns {Number}
*/
dc.utils.safeNumber = function (n) { return dc.utils.isNumber(+n) ? +n : 0;};
/**
* Return true if both arrays are equal, if both array are null these are considered equal
* @method arraysEqual
* @memberof dc.utils
* @param {Array|null} a1
* @param {Array|null} a2
* @returns {Boolean}
*/
dc.utils.arraysEqual = function (a1, a2) {
if (!a1 && !a2) {
return true;
}
if (!a1 || !a2) {
return false;
}
return a1.length === a2.length &&
// If elements are not integers/strings, we hope that it will match because of toString
// Test cases cover dates as well.
a1.every(function (elem, i) {
return elem.valueOf() === a2[i].valueOf();
});
};
// ******** Sunburst Chart ********
dc.utils.allChildren = function (node) {
var paths = [];
paths.push(node.path);
console.log('currentNode', node);
if (node.children) {
for (var i = 0; i < node.children.length; i++) {
paths = paths.concat(dc.utils.allChildren(node.children[i]));
}
}
return paths;
};
// builds a d3 Hierarchy from a collection
// TODO: turn this monster method something better.
dc.utils.toHierarchy = function (list, accessor) {
var root = {'key': 'root', 'children': []};
for (var i = 0; i < list.length; i++) {
var data = list[i];
var parts = data.key;
var value = accessor(data);
var currentNode = root;
for (var j = 0; j < parts.length; j++) {
var currentPath = parts.slice(0, j + 1);
var children = currentNode.children;
var nodeName = parts[j];
var childNode;
if (j + 1 < parts.length) {
// Not yet at the end of the sequence; move down the tree.
childNode = findChild(children, nodeName);
// If we don't already have a child node for this branch, create it.
if (childNode === void 0) {
childNode = {'key': nodeName, 'children': [], 'path': currentPath};
children.push(childNode);
}
currentNode = childNode;
} else {
// Reached the end of the sequence; create a leaf node.
childNode = {'key': nodeName, 'value': value, 'data': data, 'path': currentPath};
children.push(childNode);
}
}
}
return root;
};
function findChild (children, nodeName) {
for (var k = 0; k < children.length; k++) {
if (children[k].key === nodeName) {
return children[k];
}
}
}
dc.utils.getAncestors = function (node) {
var path = [];
var current = node;
while (current.parent) {
path.unshift(current.name);
current = current.parent;
}
return path;
};
dc.utils.arraysIdentical = function (a, b) {
var i = a.length;
if (i !== b.length) {
return false;
}
while (i--) {
if (a[i] !== b[i]) {
return false;
}
}
return true;
};
if (typeof Object.assign !== 'function') {
// Must be writable: true, enumerable: false, configurable: true
Object.defineProperty(Object, 'assign', {
value: function assign (target, varArgs) { // .length of function is 2
'use strict';
if (target === null) { // TypeError if undefined or null
throw new TypeError('Cannot convert undefined or null to object');
}
var to = Object(target);
for (var index = 1; index < arguments.length; index++) {
var nextSource = arguments[index];
if (nextSource !== null) { // Skip over if undefined or null
for (var nextKey in nextSource) {
// Avoid bugs when hasOwnProperty is shadowed
if (Object.prototype.hasOwnProperty.call(nextSource, nextKey)) {
to[nextKey] = nextSource[nextKey];
}
}
}
}
return to;
},
writable: true,
configurable: true
});
}
/**
* Provides basis logging and deprecation utilities
* @class logger
* @memberof dc
* @returns {dc.logger}
*/
dc.logger = (function () {
var _logger = {};
/**