-
Notifications
You must be signed in to change notification settings - Fork 0
/
protovis-d3.1.js
7725 lines (7261 loc) · 249 KB
/
protovis-d3.1.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
/**
* @class The built-in Array class.
* @name Array
*/
if (!Array.prototype.map) {
/**
* Creates a new array with the results of calling a provided function on
* every element in this array. Implemented in Javascript 1.6.
*
* @see <a
* href="https://developer.mozilla.org/En/Core_JavaScript_1.5_Reference/Objects/Array/Map">map</a>
* documentation.
* @param {function} f function that produces an element of the new Array from
* an element of the current one.
* @param [o] object to use as <tt>this</tt> when executing <tt>f</tt>.
*/
Array.prototype.map = function(f, o) {
var n = this.length;
var result = new Array(n);
for (var i = 0; i < n; i++) {
if (i in this) {
result[i] = f.call(o, this[i], i, this);
}
}
return result;
};
}
if (!Array.prototype.filter) {
/**
* Creates a new array with all elements that pass the test implemented by the
* provided function. Implemented in Javascript 1.6.
*
* @see <a
* href="https://developer.mozilla.org/En/Core_JavaScript_1.5_Reference/Objects/Array/filter">filter</a>
* documentation.
* @param {function} f function to test each element of the array.
* @param [o] object to use as <tt>this</tt> when executing <tt>f</tt>.
*/
Array.prototype.filter = function(f, o) {
var n = this.length;
var result = new Array();
for (var i = 0; i < n; i++) {
if (i in this) {
var v = this[i];
if (f.call(o, v, i, this)) result.push(v);
}
}
return result;
};
}
if (!Array.prototype.forEach) {
/**
* Executes a provided function once per array element. Implemented in
* Javascript 1.6.
*
* @see <a
* href="https://developer.mozilla.org/En/Core_JavaScript_1.5_Reference/Objects/Array/ForEach">forEach</a>
* documentation.
* @param {function} f function to execute for each element.
* @param [o] object to use as <tt>this</tt> when executing <tt>f</tt>.
*/
Array.prototype.forEach = function(f, o) {
var n = this.length >>> 0;
for (var i = 0; i < n; i++) {
if (i in this) f.call(o, this[i], i, this);
}
};
}
if (!Array.prototype.reduce) {
/**
* Apply a function against an accumulator and each value of the array (from
* left-to-right) as to reduce it to a single value. Implemented in Javascript
* 1.8.
*
* @see <a
* href="https://developer.mozilla.org/En/Core_JavaScript_1.5_Reference/Objects/Array/Reduce">reduce</a>
* documentation.
* @param {function} f function to execute on each value in the array.
* @param [v] object to use as the first argument to the first call of
* <tt>t</tt>.
*/
Array.prototype.reduce = function(f, v) {
var len = this.length;
if (!len && (arguments.length == 1)) {
throw new Error("reduce: empty array, no initial value");
}
var i = 0;
if (arguments.length < 2) {
while (true) {
if (i in this) {
v = this[i++];
break;
}
if (++i >= len) {
throw new Error("reduce: no values, no initial value");
}
}
}
for (; i < len; i++) {
if (i in this) {
v = f(v, this[i], i, this);
}
}
return v;
};
}
/**
* @class The built-in Date class.
* @name Date
*/
Date.__parse__ = Date.parse;
/**
* Parses a date from a string, optionally using the specified formatting. If
* only a single argument is specified (i.e., <tt>format</tt> is not specified),
* this method invokes the native implementation to guarantee
* backwards-compatibility.
*
* <p>The format string is in the same format expected by the <tt>strptime</tt>
* function in C. The following conversion specifications are supported:<ul>
*
* <li>%b - abbreviated month names.</li>
* <li>%B - full month names.</li>
* <li>%h - same as %b.</li>
* <li>%d - day of month [1,31].</li>
* <li>%e - same as %d.</li>
* <li>%H - hour (24-hour clock) [0,23].</li>
* <li>%m - month number [1,12].</li>
* <li>%M - minute [0,59].</li>
* <li>%S - second [0,61].</li>
* <li>%y - year with century [0,99].</li>
* <li>%Y - year including century.</li>
* <li>%% - %.</li>
*
* </ul>The following conversion specifications are <i>unsupported</i> (for now):<ul>
*
* <li>%a - day of week, either abbreviated or full name.</li>
* <li>%A - same as %a.</li>
* <li>%c - locale's appropriate date and time.</li>
* <li>%C - century number.</li>
* <li>%D - same as %m/%d/%y.</li>
* <li>%I - hour (12-hour clock) [1,12].</li>
* <li>%j - day number [1,366].</li>
* <li>%n - any white space.</li>
* <li>%p - locale's equivalent of a.m. or p.m.</li>
* <li>%r - same as %I:%M:%S %p.</li>
* <li>%R - same as %H:%M.</li>
* <li>%t - same as %n.</li>
* <li>%T - same as %H:%M:%S.</li>
* <li>%U - week number [0,53].</li>
* <li>%w - weekday [0,6].</li>
* <li>%W - week number [0,53].</li>
* <li>%x - locale's equivalent to %m/%d/%y.</li>
* <li>%X - locale's equivalent to %I:%M:%S %p.</li>
*
* </ul>
*
* @see <a
* href="http://www.opengroup.org/onlinepubs/007908799/xsh/strptime.html">strptime</a>
* documentation.
* @param {string} s the string to parse as a date.
* @param {string} [format] an optional format string.
* @returns {Date} the parsed date.
*/
Date.parse = function(s, format) {
if (arguments.length == 1) {
return Date.__parse__(s);
}
var year = 1970, month = 0, date = 1, hour = 0, minute = 0, second = 0;
var fields = [function() {}];
format = format.replace(/[\\\^\$\*\+\?\[\]\(\)\.\{\}]/g, "\\$&");
format = format.replace(/%[a-zA-Z0-9]/g, function(s) {
switch (s) {
// TODO %a: day of week, either abbreviated or full name
// TODO %A: same as %a
case '%b': {
fields.push(function(x) { month = {
Jan: 0, Feb: 1, Mar: 2, Apr: 3, May: 4, Jun: 5, Jul: 6, Aug: 7,
Sep: 8, Oct: 9, Nov: 10, Dec: 11
}[x]; });
return "([A-Za-z]+)";
}
case '%h':
case '%B': {
fields.push(function(x) { month = {
January: 0, February: 1, March: 2, April: 3, May: 4, June: 5,
July: 6, August: 7, September: 8, October: 9, November: 10,
December: 11
}[x]; });
return "([A-Za-z]+)";
}
// TODO %c: locale's appropriate date and time
// TODO %C: century number[0,99]
case '%e':
case '%d': {
fields.push(function(x) { date = x; });
return "([0-9]+)";
}
// TODO %D: same as %m/%d/%y
case '%H': {
fields.push(function(x) { hour = x; });
return "([0-9]+)";
}
// TODO %I: hour (12-hour clock) [1,12]
// TODO %j: day number [1,366]
case '%m': {
fields.push(function(x) { month = x - 1; });
return "([0-9]+)";
}
case '%M': {
fields.push(function(x) { minute = x; });
return "([0-9]+)";
}
// TODO %n: any white space
// TODO %p: locale's equivalent of a.m. or p.m.
// TODO %r: %I:%M:%S %p
// TODO %R: %H:%M
case '%S': {
fields.push(function(x) { second = x; });
return "([0-9]+)";
}
// TODO %t: any white space
// TODO %T: %H:%M:%S
// TODO %U: week number [00,53]
// TODO %w: weekday [0,6]
// TODO %W: week number [00, 53]
// TODO %x: locale date (%m/%d/%y)
// TODO %X: locale time (%I:%M:%S %p)
case '%y': {
fields.push(function(x) {
x = Number(x);
year = x + (((0 <= x) && (x < 69)) ? 2000
: (((x >= 69) && (x < 100) ? 1900 : 0)));
});
return "([0-9]+)";
}
case '%Y': {
fields.push(function(x) { year = x; });
return "([0-9]+)";
}
case '%%': {
fields.push(function() {});
return "%";
}
}
return s;
});
var match = s.match(format);
if (match) match.forEach(function(m, i) { fields[i](m); });
return new Date(year, month, date, hour, minute, second);
};
if (Date.prototype.toLocaleFormat) {
Date.prototype.format = Date.prototype.toLocaleFormat;
} else {
/**
* Converts a date to a string using the specified formatting. If the
* <tt>Date</tt> object already supports the <tt>toLocaleFormat</tt> method, as
* in Firefox, this is simply an alias to the built-in method.
*
* <p>The format string is in the same format expected by the <tt>strftime</tt>
* function in C. The following conversion specifications are supported:<ul>
*
* <li>%a - abbreviated weekday name.</li>
* <li>%A - full weekday name.</li>
* <li>%b - abbreviated month names.</li>
* <li>%B - full month names.</li>
* <li>%c - locale's appropriate date and time.</li>
* <li>%C - century number.</li>
* <li>%d - day of month [01,31] (zero padded).</li>
* <li>%D - same as %m/%d/%y.</li>
* <li>%e - day of month [ 1,31] (space padded).</li>
* <li>%h - same as %b.</li>
* <li>%H - hour (24-hour clock) [00,23] (zero padded).</li>
* <li>%I - hour (12-hour clock) [01,12] (zero padded).</li>
* <li>%m - month number [01,12] (zero padded).</li>
* <li>%M - minute [0,59] (zero padded).</li>
* <li>%n - newline character.</li>
* <li>%p - locale's equivalent of a.m. or p.m.</li>
* <li>%r - same as %I:%M:%S %p.</li>
* <li>%R - same as %H:%M.</li>
* <li>%S - second [00,61] (zero padded).</li>
* <li>%t - tab character.</li>
* <li>%T - same as %H:%M:%S.</li>
* <li>%x - same as %m/%d/%y.</li>
* <li>%X - same as %I:%M:%S %p.</li>
* <li>%y - year with century [00,99] (zero padded).</li>
* <li>%Y - year including century.</li>
* <li>%% - %.</li>
*
* </ul>The following conversion specifications are <i>unsupported</i> (for now):<ul>
*
* <li>%j - day number [1,366].</li>
* <li>%u - weekday number [1,7].</li>
* <li>%U - week number [00,53].</li>
* <li>%V - week number [01,53].</li>
* <li>%w - weekday number [0,6].</li>
* <li>%W - week number [00,53].</li>
* <li>%Z - timezone name or abbreviation.</li>
*
* </ul>
*
* @see <a
* href="http://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Date/toLocaleFormat">Date.toLocaleFormat</a>
* documentation.
* @see <a
* href="http://www.opengroup.org/onlinepubs/007908799/xsh/strftime.html">strftime</a>
* documentation.
* @param {string} format a format string.
* @returns {string} the formatted date.
*/
Date.prototype.format = function(format) {
function pad(n, p) { return (n < 10) ? (p || "0") + n : n; }
var d = this;
return format.replace(/%[a-zA-Z0-9]/g, function(s) {
switch (s) {
case '%a': return [
"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"
][d.getDay()];
case '%A': return [
"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday",
"Saturday"
][d.getDay()];
case '%h':
case '%b': return [
"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep",
"Oct", "Nov", "Dec"
][d.getMonth()];
case '%B': return [
"January", "February", "March", "April", "May", "June", "July",
"August", "September", "October", "November", "December"
][d.getMonth()];
case '%c': return d.toLocaleString();
case '%C': return pad(Math.floor(d.getFullYear() / 100) % 100);
case '%d': return pad(d.getDate());
case '%x':
case '%D': return pad(d.getMonth() + 1)
+ "/" + pad(d.getDate())
+ "/" + pad(d.getFullYear() % 100);
case '%e': return pad(d.getDate(), " ");
case '%H': return pad(d.getHours());
case '%I': {
var h = d.getHours() % 12;
return h ? pad(h) : 12;
}
// TODO %j: day of year as a decimal number [001,366]
case '%m': return pad(d.getMonth() + 1);
case '%M': return pad(d.getMinutes());
case '%n': return "\n";
case '%p': return d.getHours() < 12 ? "AM" : "PM";
case '%T':
case '%X':
case '%r': {
var h = d.getHours() % 12;
return (h ? pad(h) : 12)
+ ":" + pad(d.getMinutes())
+ ":" + pad(d.getSeconds())
+ " " + (d.getHours() < 12 ? "AM" : "PM");
}
case '%R': return pad(d.getHours()) + ":" + pad(d.getMinutes());
case '%S': return pad(d.getSeconds());
case '%t': return "\t";
case '%u': {
var w = d.getDay();
return w ? w : 1;
}
// TODO %U: week number (sunday first day) [00,53]
// TODO %V: week number (monday first day) [01,53] ... with weirdness
case '%w': return d.getDay();
// TODO %W: week number (monday first day) [00,53] ... with weirdness
case '%y': return pad(d.getFullYear() % 100);
case '%Y': return d.getFullYear();
// TODO %Z: timezone name or abbreviation
case '%%': return "%";
}
return s;
});
};
}
var pv = function() {/**
* The top-level Protovis namespace. All public methods and fields should be
* registered on this object. Note that core Protovis source is surrounded by an
* anonymous function, so any other declared globals will not be visible outside
* of core methods. This also allows multiple versions of Protovis to coexist,
* since each version will see their own <tt>pv</tt> namespace.
*
* @namespace The top-level Protovis namespace, <tt>pv</tt>.
*/
var pv = {};
/**
* @private Returns a prototype object suitable for extending the given class
* <tt>f</tt>. Rather than constructing a new instance of <tt>f</tt> to serve as
* the prototype (which unnecessarily runs the constructor on the created
* prototype object, potentially polluting it), an anonymous function is
* generated internally that shares the same prototype:
*
* <pre>function g() {}
* g.prototype = f.prototype;
* return new g();</pre>
*
* For more details, see Douglas Crockford's essay on prototypal inheritance.
*
* @param {function} f a constructor.
* @returns a suitable prototype object.
* @see Douglas Crockford's essay on <a
* href="http://javascript.crockford.com/prototypal.html">prototypal
* inheritance</a>.
*/
pv.extend = function(f) {
function g() {}
g.prototype = f.prototype || f;
return new g();
};
try {
eval("pv.parse = function(x) x;"); // native support
} catch (e) {
/**
* @private Parses a Protovis specification, which may use JavaScript 1.8
* function expresses, replacing those function expressions with proper
* functions such that the code can be run by a JavaScript 1.6 interpreter. This
* hack only supports function expressions (using clumsy regular expressions, no
* less), and not other JavaScript 1.8 features such as let expressions.
*
* @param {string} s a Protovis specification (i.e., a string of JavaScript 1.8
* source code).
* @returns {string} a conformant JavaScript 1.6 source code.
*/
pv.parse = function(js) { // hacky regex support
var re = new RegExp("function(\\s+\\w+)?\\([^)]*\\)\\s*", "mg"), m, d, i = 0, s = "";
while (m = re.exec(js)) {
var j = m.index + m[0].length;
if (js.charAt(j--) != '{') {
s += js.substring(i, j) + "{return ";
i = j;
for (var p = 0; p >= 0 && j < js.length; j++) {
var c = js.charAt(j);
switch (c) {
case '"': case '\'': {
while (++j < js.length && (d = js.charAt(j)) != c) {
if (d == '\\') j++;
}
break;
}
case '[': case '(': p++; break;
case ']': case ')': p--; break;
case ';':
case ',': if (p == 0) p--; break;
}
}
s += pv.parse(js.substring(i, --j)) + ";}";
i = j;
}
re.lastIndex = j;
}
s += js.substring(i);
return s;
};
}
/**
* Returns the passed-in argument, <tt>x</tt>; the identity function. This method
* is provided for convenience since it is used as the default behavior for a
* number of property functions.
*
* @param x a value.
* @returns the value <tt>x</tt>.
*/
pv.identity = function(x) { return x; };
/**
* Returns <tt>this.index</tt>. This method is provided for convenience for use
* with scales. For example, to color bars by their index, say:
*
* <pre>.fillStyle(pv.Colors.category10().by(pv.index))</pre>
*
* This method is equivalent to <tt>function() this.index</tt>, but more
* succinct. Note that the <tt>index</tt> property is also supported for
* accessor functions with {@link pv.max}, {@link pv.min} and other array
* utility methods.
*
* @see pv.Scale
* @see pv.Mark#index
*/
pv.index = function() { return this.index; };
/**
* Returns <tt>this.childIndex</tt>. This method is provided for convenience for
* use with scales. For example, to color bars by their child index, say:
*
* <pre>.fillStyle(pv.Colors.category10().by(pv.child))</pre>
*
* This method is equivalent to <tt>function() this.childIndex</tt>, but more
* succinct.
*
* @see pv.Scale
* @see pv.Mark#childIndex
*/
pv.child = function() { return this.childIndex; };
/**
* Returns <tt>this.parent.index</tt>. This method is provided for convenience
* for use with scales. This method is provided for convenience for use with
* scales. For example, to color bars by their parent index, say:
*
* <pre>.fillStyle(pv.Colors.category10().by(pv.parent))</pre>
*
* Tthis method is equivalent to <tt>function() this.parent.index</tt>, but more
* succinct.
*
* @see pv.Scale
* @see pv.Mark#index
*/
pv.parent = function() { return this.parent.index; };
/**
* Returns an array of numbers, starting at <tt>start</tt>, incrementing by
* <tt>step</tt>, until <tt>stop</tt> is reached. The stop value is exclusive. If
* only a single argument is specified, this value is interpeted as the
* <i>stop</i> value, with the <i>start</i> value as zero. If only two arguments
* are specified, the step value is implied to be one.
*
* <p>The method is modeled after the built-in <tt>range</tt> method from
* Python. See the Python documentation for more details.
*
* @see <a href="http://docs.python.org/library/functions.html#range">Python range</a>
* @param {number} [start] the start value.
* @param {number} stop the stop value.
* @param {number} [step] the step value.
* @returns {number[]} an array of numbers.
*/
pv.range = function(start, stop, step) {
if (arguments.length == 1) {
stop = start;
start = 0;
}
if (step == undefined) step = 1;
else if (!step) throw new Error("step must be non-zero");
var array = [], i = 0, j;
if (step < 0) {
while ((j = start + step * i++) > stop) {
array.push(j);
}
} else {
while ((j = start + step * i++) < stop) {
array.push(j);
}
}
return array;
};
/**
* Returns a random number in the range [<tt>min</tt>, <tt>max</tt>) that is a
* multiple of <tt>step</tt>. More specifically, the returned number is of the
* form <tt>min</tt> + <i>n</i> * <tt>step</tt>, where <i>n</i> is a nonnegative
* integer. If <tt>step</tt> is not specified, it defaults to 1, returning a
* random integer if <tt>min</tt> is also an integer.
*
* @param min {number} minimum value.
* @param [max] {number} maximum value.
* @param [step] {numbeR} step value.
*/
pv.random = function(min, max, step) {
if (arguments.length == 1) {
max = min;
min = 0;
}
if (step == undefined) {
step = 1;
}
return step
? (Math.floor(Math.random() * (max - min) / step) * step + min)
: (Math.random() * (max - min) + min);
};
/**
* Concatenates the specified array with itself <i>n</i> times. For example,
* <tt>pv.repeat([1, 2])</tt> returns [1, 2, 1, 2].
*
* @param {array} a an array.
* @param {number} [n] the number of times to repeat; defaults to two.
* @returns {array} an array that repeats the specified array.
*/
pv.repeat = function(array, n) {
if (arguments.length == 1) n = 2;
return pv.blend(pv.range(n).map(function() { return array; }));
};
/**
* Given two arrays <tt>a</tt> and <tt>b</tt>, <style
* type="text/css">sub{line-height:0}</style> returns an array of all possible
* pairs of elements [a<sub>i</sub>, b<sub>j</sub>]. The outer loop is on array
* <i>a</i>, while the inner loop is on <i>b</i>, such that the order of
* returned elements is [a<sub>0</sub>, b<sub>0</sub>], [a<sub>0</sub>,
* b<sub>1</sub>], ... [a<sub>0</sub>, b<sub>m</sub>], [a<sub>1</sub>,
* b<sub>0</sub>], [a<sub>1</sub>, b<sub>1</sub>], ... [a<sub>1</sub>,
* b<sub>m</sub>], ... [a<sub>n</sub>, b<sub>m</sub>]. If either array is empty,
* an empty array is returned.
*
* @param {array} a an array.
* @param {array} b an array.
* @returns {array} an array of pairs of elements in <tt>a</tt> and <tt>b</tt>.
*/
pv.cross = function(a, b) {
var array = [];
for (var i = 0, n = a.length, m = b.length; i < n; i++) {
for (var j = 0, x = a[i]; j < m; j++) {
array.push([x, b[j]]);
}
}
return array;
};
/**
* Given the specified array of arrays, concatenates the arrays into a single
* array. If the individual arrays are explicitly known, an alternative to blend
* is to use JavaScript's <tt>concat</tt> method directly. These two equivalent
* expressions:<ul>
*
* <li><tt>pv.blend([[1, 2, 3], ["a", "b", "c"]])</tt>
* <li><tt>[1, 2, 3].concat(["a", "b", "c"])</tt>
*
* </ul>return [1, 2, 3, "a", "b", "c"].
*
* @param {array[]} arrays an array of arrays.
* @returns {array} an array containing all the elements of each array in
* <tt>arrays</tt>.
*/
pv.blend = function(arrays) {
return Array.prototype.concat.apply([], arrays);
};
/**
* Given the specified array of arrays, <style
* type="text/css">sub{line-height:0}</style> transposes each element
* array<sub>ij</sub> with array<sub>ji</sub>. If the array has dimensions
* <i>n</i>×<i>m</i>, it will have dimensions <i>m</i>×<i>n</i>
* after this method returns. This method transposes the elements of the array
* in place, mutating the array, and returning a reference to the array.
*
* @param {array[]} arrays an array of arrays.
* @returns {array[]} the passed-in array, after transposing the elements.
*/
pv.transpose = function(arrays) {
var n = arrays.length, m = pv.max(arrays, function(d) { return d.length; });
if (m > n) {
arrays.length = m;
for (var i = n; i < m; i++) {
arrays[i] = new Array(n);
}
for (var i = 0; i < n; i++) {
for (var j = i + 1; j < m; j++) {
var t = arrays[i][j];
arrays[i][j] = arrays[j][i];
arrays[j][i] = t;
}
}
} else {
for (var i = 0; i < m; i++) {
arrays[i].length = n;
}
for (var i = 0; i < n; i++) {
for (var j = 0; j < i; j++) {
var t = arrays[i][j];
arrays[i][j] = arrays[j][i];
arrays[j][i] = t;
}
}
}
arrays.length = m;
for (var i = 0; i < m; i++) {
arrays[i].length = n;
}
return arrays;
};
/**
* Returns all of the property names (keys) of the specified object (a map). The
* order of the returned array is not defined.
*
* @param map an object.
* @returns {string[]} an array of strings corresponding to the keys.
* @see #entries
*/
pv.keys = function(map) {
var array = [];
for (var key in map) {
array.push(key);
}
return array;
};
/**
* Returns all of the entries (key-value pairs) of the specified object (a
* map). The order of the returned array is not defined. Each key-value pair is
* represented as an object with <tt>key</tt> and <tt>value</tt> attributes,
* e.g., <tt>{key: "foo", value: 42}</tt>.
*
* @param map an object.
* @returns {array} an array of key-value pairs corresponding to the keys.
*/
pv.entries = function(map) {
var array = [];
for (var key in map) {
array.push({ key: key, value: map[key] });
}
return array;
};
/**
* Returns all of the values (attribute values) of the specified object (a
* map). The order of the returned array is not defined.
*
* @param map an object.
* @returns {array} an array of objects corresponding to the values.
* @see #entries
*/
pv.values = function(map) {
var array = [];
for (var key in map) {
array.push(map[key]);
}
return array;
};
/**
* @private A private variant of Array.prototype.map that supports the index
* property.
*/
function map(array, f) {
var o = {};
return f
? array.map(function(d, i) { o.index = i; return f.call(o, d); })
: array.slice();
};
/**
* Returns a normalized copy of the specified array, such that the sum of the
* returned elements sum to one. If the specified array is not an array of
* numbers, an optional accessor function <tt>f</tt> can be specified to map the
* elements to numbers. For example, if <tt>array</tt> is an array of objects,
* and each object has a numeric property "foo", the expression
*
* <pre>pv.normalize(array, function(d) d.foo)</pre>
*
* returns a normalized array on the "foo" property. If an accessor function is
* not specified, the identity function is used. Accessor functions can refer to
* <tt>this.index</tt>.
*
* @param {array} array an array of objects, or numbers.
* @param {function} [f] an optional accessor function.
* @returns {number[]} an array of numbers that sums to one.
*/
pv.normalize = function(array, f) {
var norm = map(array, f), sum = pv.sum(norm);
for (var i = 0; i < norm.length; i++) norm[i] /= sum;
return norm;
};
/**
* Returns the sum of the specified array. If the specified array is not an
* array of numbers, an optional accessor function <tt>f</tt> can be specified
* to map the elements to numbers. See {@link #normalize} for an example.
* Accessor functions can refer to <tt>this.index</tt>.
*
* @param {array} array an array of objects, or numbers.
* @param {function} [f] an optional accessor function.
* @returns {number} the sum of the specified array.
*/
pv.sum = function(array, f) {
var o = {};
return array.reduce(f
? function(p, d, i) { o.index = i; return p + f.call(o, d); }
: function(p, d) { return p + d; }, 0);
};
/**
* Returns the maximum value of the specified array. If the specified array is
* not an array of numbers, an optional accessor function <tt>f</tt> can be
* specified to map the elements to numbers. See {@link #normalize} for an
* example. Accessor functions can refer to <tt>this.index</tt>.
*
* @param {array} array an array of objects, or numbers.
* @param {function} [f] an optional accessor function.
* @returns {number} the maximum value of the specified array.
*/
pv.max = function(array, f) {
if (f == pv.index) return array.length - 1;
return Math.max.apply(null, f ? map(array, f) : array);
};
/**
* Returns the index of the maximum value of the specified array. If the
* specified array is not an array of numbers, an optional accessor function
* <tt>f</tt> can be specified to map the elements to numbers. See
* {@link #normalize} for an example. Accessor functions can refer to
* <tt>this.index</tt>.
*
* @param {array} array an array of objects, or numbers.
* @param {function} [f] an optional accessor function.
* @returns {number} the index of the maximum value of the specified array.
*/
pv.max.index = function(array, f) {
if (f == pv.index) return array.length - 1;
if (!f) f = pv.identity;
var maxi = -1, maxx = -Infinity, o = {};
for (var i = 0; i < array.length; i++) {
o.index = i;
var x = f.call(o, array[i]);
if (x > maxx) {
maxx = x;
maxi = i;
}
}
return maxi;
}
/**
* Returns the minimum value of the specified array of numbers. If the specified
* array is not an array of numbers, an optional accessor function <tt>f</tt>
* can be specified to map the elements to numbers. See {@link #normalize} for
* an example. Accessor functions can refer to <tt>this.index</tt>.
*
* @param {array} array an array of objects, or numbers.
* @param {function} [f] an optional accessor function.
* @returns {number} the minimum value of the specified array.
*/
pv.min = function(array, f) {
if (f == pv.index) return 0;
return Math.min.apply(null, f ? map(array, f) : array);
};
/**
* Returns the index of the minimum value of the specified array. If the
* specified array is not an array of numbers, an optional accessor function
* <tt>f</tt> can be specified to map the elements to numbers. See
* {@link #normalize} for an example. Accessor functions can refer to
* <tt>this.index</tt>.
*
* @param {array} array an array of objects, or numbers.
* @param {function} [f] an optional accessor function.
* @returns {number} the index of the minimum value of the specified array.
*/
pv.min.index = function(array, f) {
if (f == pv.index) return 0;
if (!f) f = pv.identity;
var mini = -1, minx = Infinity, o = {};
for (var i = 0; i < array.length; i++) {
o.index = i;
var x = f.call(o, array[i]);
if (x < minx) {
minx = x;
mini = i;
}
}
return mini;
}
/**
* Returns the arithmetic mean, or average, of the specified array. If the
* specified array is not an array of numbers, an optional accessor function
* <tt>f</tt> can be specified to map the elements to numbers. See
* {@link #normalize} for an example. Accessor functions can refer to
* <tt>this.index</tt>.
*
* @param {array} array an array of objects, or numbers.
* @param {function} [f] an optional accessor function.
* @returns {number} the mean of the specified array.
*/
pv.mean = function(array, f) {
return pv.sum(array, f) / array.length;
};
/**
* Returns the median of the specified array. If the specified array is not an
* array of numbers, an optional accessor function <tt>f</tt> can be specified
* to map the elements to numbers. See {@link #normalize} for an example.
* Accessor functions can refer to <tt>this.index</tt>.
*
* @param {array} array an array of objects, or numbers.
* @param {function} [f] an optional accessor function.
* @returns {number} the median of the specified array.
*/
pv.median = function(array, f) {
if (f == pv.index) return (array.length - 1) / 2;
array = map(array, f).sort(pv.naturalOrder);
if (array.length % 2) return array[Math.floor(array.length / 2)];
var i = array.length / 2;
return (array[i - 1] + array[i]) / 2;
};
/**
* Returns a map constructed from the specified <tt>keys</tt>, using the
* function <tt>f</tt> to compute the value for each key. The single argument to
* the value function is the key. The callback is invoked only for indexes of
* the array which have assigned values; it is not invoked for indexes which
* have been deleted or which have never been assigned values.
*
* <p>For example, this expression creates a map from strings to string length:
*
* <pre>pv.dict(["one", "three", "seventeen"], function(s) s.length)</pre>
*
* The returned value is <tt>{one: 3, three: 5, seventeen: 9}</tt>. Accessor
* functions can refer to <tt>this.index</tt>.
*
* @param {array} keys an array.
* @param {function} f a value function.
* @returns a map from keys to values.
*/
pv.dict = function(keys, f) {
var m = {}, o = {};
for (var i = 0; i < keys.length; i++) {
if (i in keys) {
var k = keys[i];
o.index = i;
m[k] = f.call(o, k);
}
}
return m;
};
/**
* Returns a permutation of the specified array, using the specified array of
* indexes. The returned array contains the corresponding element in
* <tt>array</tt> for each index in <tt>indexes</tt>, in order. For example,
*
* <pre>pv.permute(["a", "b", "c"], [1, 2, 0])</pre>
*
* returns <tt>["b", "c", "a"]</tt>. It is acceptable for the array of indexes
* to be a different length from the array of elements, and for indexes to be
* duplicated or omitted. The optional accessor function <tt>f</tt> can be used
* to perform a simultaneous mapping of the array elements. Accessor functions
* can refer to <tt>this.index</tt>.
*
* @param {array} array an array.
* @param {number[]} indexes an array of indexes into <tt>array</tt>.
* @param {function} [f] an optional accessor function.
* @returns {array} an array of elements from <tt>array</tt>; a permutation.
*/
pv.permute = function(array, indexes, f) {
if (!f) f = pv.identity;
var p = new Array(indexes.length), o = {};
indexes.forEach(function(j, i) { o.index = j; p[i] = f.call(o, array[j]); });
return p;
};
/**
* Returns a map from key to index for the specified <tt>keys</tt> array. For
* example,
*
* <pre>pv.numerate(["a", "b", "c"])</pre>
*
* returns <tt>{a: 0, b: 1, c: 2}</tt>. Note that since JavaScript maps only
* support string keys, <tt>keys</tt> must contain strings, or other values that
* naturally map to distinct string values. Alternatively, an optional accessor
* function <tt>f</tt> can be specified to compute the string key for the given
* element. Accessor functions can refer to <tt>this.index</tt>.
*
* @param {array} keys an array, usually of string keys.
* @param {function} [f] an optional key function.
* @returns a map from key to index.
*/
pv.numerate = function(keys, f) {
if (!f) f = pv.identity;
var map = {}, o = {};
keys.forEach(function(x, i) { o.index = i; map[f.call(o, x)] = i; });
return map;
};
/**
* The comparator function for natural order. This can be used in conjunction with
* the built-in array <tt>sort</tt> method to sort elements by their natural
* order, ascending. Note that if no comparator function is specified to the
* built-in <tt>sort</tt> method, the default order is lexicographic, <i>not</i>
* natural!
*
* @see <a
* href="http://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Array/sort">Array.sort</a>.
* @param a an element to compare.
* @param b an element to compare.
* @returns {number} negative if a < b; positive if a > b; otherwise 0.
*/
pv.naturalOrder = function(a, b) {
return (a < b) ? -1 : ((a > b) ? 1 : 0);
};