Iterator optimization - peek-ahead is optimized, and, remove idx_, which is not required.
[dygraphs.git] / dygraph-utils.js
1 /**
2 * @license
3 * Copyright 2011 Dan Vanderkam (danvdk@gmail.com)
4 * MIT-licensed (http://opensource.org/licenses/MIT)
5 */
6
7 /**
8 * @fileoverview This file contains utility functions used by dygraphs. These
9 * are typically static (i.e. not related to any particular dygraph). Examples
10 * include date/time formatting functions, basic algorithms (e.g. binary
11 * search) and generic DOM-manipulation functions.
12 */
13
14 /*jshint globalstrict: true */
15 /*global Dygraph:false, G_vmlCanvasManager:false, Node:false, printStackTrace: false */
16 "use strict";
17
18 Dygraph.LOG_SCALE = 10;
19 Dygraph.LN_TEN = Math.log(Dygraph.LOG_SCALE);
20
21 /** @private */
22 Dygraph.log10 = function(x) {
23 return Math.log(x) / Dygraph.LN_TEN;
24 };
25
26 // Various logging levels.
27 Dygraph.DEBUG = 1;
28 Dygraph.INFO = 2;
29 Dygraph.WARNING = 3;
30 Dygraph.ERROR = 3;
31
32 // Set this to log stack traces on warnings, etc.
33 // This requires stacktrace.js, which is up to you to provide.
34 // A copy can be found in the dygraphs repo, or at
35 // https://github.com/eriwen/javascript-stacktrace
36 Dygraph.LOG_STACK_TRACES = false;
37
38 /** A dotted line stroke pattern. */
39 Dygraph.DOTTED_LINE = [2, 2];
40 /** A dashed line stroke pattern. */
41 Dygraph.DASHED_LINE = [7, 3];
42 /** A dot dash stroke pattern. */
43 Dygraph.DOT_DASH_LINE = [7, 2, 2, 2];
44
45 /**
46 * @private
47 * Log an error on the JS console at the given severity.
48 * @param { Integer } severity One of Dygraph.{DEBUG,INFO,WARNING,ERROR}
49 * @param { String } The message to log.
50 */
51 Dygraph.log = function(severity, message) {
52 var st;
53 if (typeof(printStackTrace) != 'undefined') {
54 // Remove uninteresting bits: logging functions and paths.
55 st = printStackTrace({guess:false});
56 while (st[0].indexOf("stacktrace") != -1) {
57 st.splice(0, 1);
58 }
59
60 st.splice(0, 2);
61 for (var i = 0; i < st.length; i++) {
62 st[i] = st[i].replace(/\([^)]*\/(.*)\)/, '@$1')
63 .replace(/\@.*\/([^\/]*)/, '@$1')
64 .replace('[object Object].', '');
65 }
66 var top_msg = st.splice(0, 1)[0];
67 message += ' (' + top_msg.replace(/^.*@ ?/, '') + ')';
68 }
69
70 if (typeof(console) != 'undefined') {
71 switch (severity) {
72 case Dygraph.DEBUG:
73 console.debug('dygraphs: ' + message);
74 break;
75 case Dygraph.INFO:
76 console.info('dygraphs: ' + message);
77 break;
78 case Dygraph.WARNING:
79 console.warn('dygraphs: ' + message);
80 break;
81 case Dygraph.ERROR:
82 console.error('dygraphs: ' + message);
83 break;
84 }
85 }
86
87 if (Dygraph.LOG_STACK_TRACES) {
88 console.log(st.join('\n'));
89 }
90 };
91
92 /** @private */
93 Dygraph.info = function(message) {
94 Dygraph.log(Dygraph.INFO, message);
95 };
96 /** @private */
97 Dygraph.prototype.info = Dygraph.info;
98
99 /** @private */
100 Dygraph.warn = function(message) {
101 Dygraph.log(Dygraph.WARNING, message);
102 };
103 /** @private */
104 Dygraph.prototype.warn = Dygraph.warn;
105
106 /** @private */
107 Dygraph.error = function(message) {
108 Dygraph.log(Dygraph.ERROR, message);
109 };
110 /** @private */
111 Dygraph.prototype.error = Dygraph.error;
112
113 /**
114 * @private
115 * Return the 2d context for a dygraph canvas.
116 *
117 * This method is only exposed for the sake of replacing the function in
118 * automated tests, e.g.
119 *
120 * var oldFunc = Dygraph.getContext();
121 * Dygraph.getContext = function(canvas) {
122 * var realContext = oldFunc(canvas);
123 * return new Proxy(realContext);
124 * };
125 */
126 Dygraph.getContext = function(canvas) {
127 return canvas.getContext("2d");
128 };
129
130 /**
131 * @private
132 * Add an event handler. This smooths a difference between IE and the rest of
133 * the world.
134 * @param { DOM element } elem The element to add the event to.
135 * @param { String } type The type of the event, e.g. 'click' or 'mousemove'.
136 * @param { Function } fn The function to call on the event. The function takes
137 * one parameter: the event object.
138 */
139 Dygraph.addEvent = function addEvent(elem, type, fn) {
140 if (elem.addEventListener) {
141 elem.addEventListener(type, fn, false);
142 } else {
143 elem[type+fn] = function(){fn(window.event);};
144 elem.attachEvent('on'+type, elem[type+fn]);
145 }
146 };
147
148 /**
149 * @private
150 * Add an event handler. This event handler is kept until the graph is
151 * destroyed with a call to graph.destroy().
152 *
153 * @param { DOM element } elem The element to add the event to.
154 * @param { String } type The type of the event, e.g. 'click' or 'mousemove'.
155 * @param { Function } fn The function to call on the event. The function takes
156 * one parameter: the event object.
157 */
158 Dygraph.prototype.addEvent = function addEvent(elem, type, fn) {
159 Dygraph.addEvent(elem, type, fn);
160 this.registeredEvents_.push({ elem : elem, type : type, fn : fn });
161 };
162
163 /**
164 * @private
165 * Remove an event handler. This smooths a difference between IE and the rest of
166 * the world.
167 * @param { DOM element } elem The element to add the event to.
168 * @param { String } type The type of the event, e.g. 'click' or 'mousemove'.
169 * @param { Function } fn The function to call on the event. The function takes
170 * one parameter: the event object.
171 */
172 Dygraph.removeEvent = function addEvent(elem, type, fn) {
173 if (elem.removeEventListener) {
174 elem.removeEventListener(type, fn, false);
175 } else {
176 elem.detachEvent('on'+type, elem[type+fn]);
177 elem[type+fn] = null;
178 }
179 };
180
181 /**
182 * @private
183 * Cancels further processing of an event. This is useful to prevent default
184 * browser actions, e.g. highlighting text on a double-click.
185 * Based on the article at
186 * http://www.switchonthecode.com/tutorials/javascript-tutorial-the-scroll-wheel
187 * @param { Event } e The event whose normal behavior should be canceled.
188 */
189 Dygraph.cancelEvent = function(e) {
190 e = e ? e : window.event;
191 if (e.stopPropagation) {
192 e.stopPropagation();
193 }
194 if (e.preventDefault) {
195 e.preventDefault();
196 }
197 e.cancelBubble = true;
198 e.cancel = true;
199 e.returnValue = false;
200 return false;
201 };
202
203 /**
204 * Convert hsv values to an rgb(r,g,b) string. Taken from MochiKit.Color. This
205 * is used to generate default series colors which are evenly spaced on the
206 * color wheel.
207 * @param { Number } hue Range is 0.0-1.0.
208 * @param { Number } saturation Range is 0.0-1.0.
209 * @param { Number } value Range is 0.0-1.0.
210 * @return { String } "rgb(r,g,b)" where r, g and b range from 0-255.
211 * @private
212 */
213 Dygraph.hsvToRGB = function (hue, saturation, value) {
214 var red;
215 var green;
216 var blue;
217 if (saturation === 0) {
218 red = value;
219 green = value;
220 blue = value;
221 } else {
222 var i = Math.floor(hue * 6);
223 var f = (hue * 6) - i;
224 var p = value * (1 - saturation);
225 var q = value * (1 - (saturation * f));
226 var t = value * (1 - (saturation * (1 - f)));
227 switch (i) {
228 case 1: red = q; green = value; blue = p; break;
229 case 2: red = p; green = value; blue = t; break;
230 case 3: red = p; green = q; blue = value; break;
231 case 4: red = t; green = p; blue = value; break;
232 case 5: red = value; green = p; blue = q; break;
233 case 6: // fall through
234 case 0: red = value; green = t; blue = p; break;
235 }
236 }
237 red = Math.floor(255 * red + 0.5);
238 green = Math.floor(255 * green + 0.5);
239 blue = Math.floor(255 * blue + 0.5);
240 return 'rgb(' + red + ',' + green + ',' + blue + ')';
241 };
242
243 // The following functions are from quirksmode.org with a modification for Safari from
244 // http://blog.firetree.net/2005/07/04/javascript-find-position/
245 // http://www.quirksmode.org/js/findpos.html
246 // ... and modifications to support scrolling divs.
247
248 /**
249 * Find the x-coordinate of the supplied object relative to the left side
250 * of the page.
251 * @private
252 */
253 Dygraph.findPosX = function(obj) {
254 var curleft = 0;
255 if(obj.offsetParent) {
256 var copyObj = obj;
257 while(1) {
258 curleft += copyObj.offsetLeft;
259 if(!copyObj.offsetParent) {
260 break;
261 }
262 copyObj = copyObj.offsetParent;
263 }
264 } else if(obj.x) {
265 curleft += obj.x;
266 }
267 // This handles the case where the object is inside a scrolled div.
268 while(obj && obj != document.body) {
269 curleft -= obj.scrollLeft;
270 obj = obj.parentNode;
271 }
272 return curleft;
273 };
274
275 /**
276 * Find the y-coordinate of the supplied object relative to the top of the
277 * page.
278 * @private
279 */
280 Dygraph.findPosY = function(obj) {
281 var curtop = 0;
282 if(obj.offsetParent) {
283 var copyObj = obj;
284 while(1) {
285 curtop += copyObj.offsetTop;
286 if(!copyObj.offsetParent) {
287 break;
288 }
289 copyObj = copyObj.offsetParent;
290 }
291 } else if(obj.y) {
292 curtop += obj.y;
293 }
294 // This handles the case where the object is inside a scrolled div.
295 while(obj && obj != document.body) {
296 curtop -= obj.scrollTop;
297 obj = obj.parentNode;
298 }
299 return curtop;
300 };
301
302 /**
303 * @private
304 * Returns the x-coordinate of the event in a coordinate system where the
305 * top-left corner of the page (not the window) is (0,0).
306 * Taken from MochiKit.Signal
307 */
308 Dygraph.pageX = function(e) {
309 if (e.pageX) {
310 return (!e.pageX || e.pageX < 0) ? 0 : e.pageX;
311 } else {
312 var de = document;
313 var b = document.body;
314 return e.clientX +
315 (de.scrollLeft || b.scrollLeft) -
316 (de.clientLeft || 0);
317 }
318 };
319
320 /**
321 * @private
322 * Returns the y-coordinate of the event in a coordinate system where the
323 * top-left corner of the page (not the window) is (0,0).
324 * Taken from MochiKit.Signal
325 */
326 Dygraph.pageY = function(e) {
327 if (e.pageY) {
328 return (!e.pageY || e.pageY < 0) ? 0 : e.pageY;
329 } else {
330 var de = document;
331 var b = document.body;
332 return e.clientY +
333 (de.scrollTop || b.scrollTop) -
334 (de.clientTop || 0);
335 }
336 };
337
338 /**
339 * @private
340 * @param { Number } x The number to consider.
341 * @return { Boolean } Whether the number is zero or NaN.
342 */
343 // TODO(danvk): rename this function to something like 'isNonZeroNan'.
344 // TODO(danvk): determine when else this returns false (e.g. for undefined or null)
345 Dygraph.isOK = function(x) {
346 return x && !isNaN(x);
347 };
348
349 /**
350 * @private
351 * @param { Object } p The point to consider, valid points are {x, y} objects
352 * @param { Boolean } allowNaNY Treat point with y=NaN as valid
353 * @return { Boolean } Whether the point has numeric x and y.
354 */
355 Dygraph.isValidPoint = function(p, allowNaNY) {
356 if (!p) return false; // null or undefined object
357 if (p.yval === null) return false; // missing point
358 if (p.x === null || p.x === undefined) return false;
359 if (p.y === null || p.y === undefined) return false;
360 if (isNaN(p.x) || (!allowNaNY && isNaN(p.y))) return false;
361 return true;
362 };
363
364 /**
365 * Number formatting function which mimicks the behavior of %g in printf, i.e.
366 * either exponential or fixed format (without trailing 0s) is used depending on
367 * the length of the generated string. The advantage of this format is that
368 * there is a predictable upper bound on the resulting string length,
369 * significant figures are not dropped, and normal numbers are not displayed in
370 * exponential notation.
371 *
372 * NOTE: JavaScript's native toPrecision() is NOT a drop-in replacement for %g.
373 * It creates strings which are too long for absolute values between 10^-4 and
374 * 10^-6, e.g. '0.00001' instead of '1e-5'. See tests/number-format.html for
375 * output examples.
376 *
377 * @param {Number} x The number to format
378 * @param {Number} opt_precision The precision to use, default 2.
379 * @return {String} A string formatted like %g in printf. The max generated
380 * string length should be precision + 6 (e.g 1.123e+300).
381 */
382 Dygraph.floatFormat = function(x, opt_precision) {
383 // Avoid invalid precision values; [1, 21] is the valid range.
384 var p = Math.min(Math.max(1, opt_precision || 2), 21);
385
386 // This is deceptively simple. The actual algorithm comes from:
387 //
388 // Max allowed length = p + 4
389 // where 4 comes from 'e+n' and '.'.
390 //
391 // Length of fixed format = 2 + y + p
392 // where 2 comes from '0.' and y = # of leading zeroes.
393 //
394 // Equating the two and solving for y yields y = 2, or 0.00xxxx which is
395 // 1.0e-3.
396 //
397 // Since the behavior of toPrecision() is identical for larger numbers, we
398 // don't have to worry about the other bound.
399 //
400 // Finally, the argument for toExponential() is the number of trailing digits,
401 // so we take off 1 for the value before the '.'.
402 return (Math.abs(x) < 1.0e-3 && x !== 0.0) ?
403 x.toExponential(p - 1) : x.toPrecision(p);
404 };
405
406 /**
407 * @private
408 * Converts '9' to '09' (useful for dates)
409 */
410 Dygraph.zeropad = function(x) {
411 if (x < 10) return "0" + x; else return "" + x;
412 };
413
414 /**
415 * Return a string version of the hours, minutes and seconds portion of a date.
416 * @param {Number} date The JavaScript date (ms since epoch)
417 * @return {String} A time of the form "HH:MM:SS"
418 * @private
419 */
420 Dygraph.hmsString_ = function(date) {
421 var zeropad = Dygraph.zeropad;
422 var d = new Date(date);
423 if (d.getSeconds()) {
424 return zeropad(d.getHours()) + ":" +
425 zeropad(d.getMinutes()) + ":" +
426 zeropad(d.getSeconds());
427 } else {
428 return zeropad(d.getHours()) + ":" + zeropad(d.getMinutes());
429 }
430 };
431
432 /**
433 * Round a number to the specified number of digits past the decimal point.
434 * @param {Number} num The number to round
435 * @param {Number} places The number of decimals to which to round
436 * @return {Number} The rounded number
437 * @private
438 */
439 Dygraph.round_ = function(num, places) {
440 var shift = Math.pow(10, places);
441 return Math.round(num * shift)/shift;
442 };
443
444 /**
445 * @private
446 * Implementation of binary search over an array.
447 * Currently does not work when val is outside the range of arry's values.
448 * @param { Integer } val the value to search for
449 * @param { Integer[] } arry is the value over which to search
450 * @param { Integer } abs If abs > 0, find the lowest entry greater than val
451 * If abs < 0, find the highest entry less than val.
452 * if abs == 0, find the entry that equals val.
453 * @param { Integer } [low] The first index in arry to consider (optional)
454 * @param { Integer } [high] The last index in arry to consider (optional)
455 */
456 Dygraph.binarySearch = function(val, arry, abs, low, high) {
457 if (low === null || low === undefined ||
458 high === null || high === undefined) {
459 low = 0;
460 high = arry.length - 1;
461 }
462 if (low > high) {
463 return -1;
464 }
465 if (abs === null || abs === undefined) {
466 abs = 0;
467 }
468 var validIndex = function(idx) {
469 return idx >= 0 && idx < arry.length;
470 };
471 var mid = parseInt((low + high) / 2, 10);
472 var element = arry[mid];
473 if (element == val) {
474 return mid;
475 }
476
477 var idx;
478 if (element > val) {
479 if (abs > 0) {
480 // Accept if element > val, but also if prior element < val.
481 idx = mid - 1;
482 if (validIndex(idx) && arry[idx] < val) {
483 return mid;
484 }
485 }
486 return Dygraph.binarySearch(val, arry, abs, low, mid - 1);
487 }
488 if (element < val) {
489 if (abs < 0) {
490 // Accept if element < val, but also if prior element > val.
491 idx = mid + 1;
492 if (validIndex(idx) && arry[idx] > val) {
493 return mid;
494 }
495 }
496 return Dygraph.binarySearch(val, arry, abs, mid + 1, high);
497 }
498 };
499
500 /**
501 * @private
502 * Parses a date, returning the number of milliseconds since epoch. This can be
503 * passed in as an xValueParser in the Dygraph constructor.
504 * TODO(danvk): enumerate formats that this understands.
505 * @param {String} A date in YYYYMMDD format.
506 * @return {Number} Milliseconds since epoch.
507 */
508 Dygraph.dateParser = function(dateStr) {
509 var dateStrSlashed;
510 var d;
511
512 // Let the system try the format first, with one caveat:
513 // YYYY-MM-DD[ HH:MM:SS] is interpreted as UTC by a variety of browsers.
514 // dygraphs displays dates in local time, so this will result in surprising
515 // inconsistencies. But if you specify "T" or "Z" (i.e. YYYY-MM-DDTHH:MM:SS),
516 // then you probably know what you're doing, so we'll let you go ahead.
517 // Issue: http://code.google.com/p/dygraphs/issues/detail?id=255
518 if (dateStr.search("-") == -1 ||
519 dateStr.search("T") != -1 || dateStr.search("Z") != -1) {
520 d = Dygraph.dateStrToMillis(dateStr);
521 if (d && !isNaN(d)) return d;
522 }
523
524 if (dateStr.search("-") != -1) { // e.g. '2009-7-12' or '2009-07-12'
525 dateStrSlashed = dateStr.replace("-", "/", "g");
526 while (dateStrSlashed.search("-") != -1) {
527 dateStrSlashed = dateStrSlashed.replace("-", "/");
528 }
529 d = Dygraph.dateStrToMillis(dateStrSlashed);
530 } else if (dateStr.length == 8) { // e.g. '20090712'
531 // TODO(danvk): remove support for this format. It's confusing.
532 dateStrSlashed = dateStr.substr(0,4) + "/" + dateStr.substr(4,2) + "/" +
533 dateStr.substr(6,2);
534 d = Dygraph.dateStrToMillis(dateStrSlashed);
535 } else {
536 // Any format that Date.parse will accept, e.g. "2009/07/12" or
537 // "2009/07/12 12:34:56"
538 d = Dygraph.dateStrToMillis(dateStr);
539 }
540
541 if (!d || isNaN(d)) {
542 Dygraph.error("Couldn't parse " + dateStr + " as a date");
543 }
544 return d;
545 };
546
547 /**
548 * @private
549 * This is identical to JavaScript's built-in Date.parse() method, except that
550 * it doesn't get replaced with an incompatible method by aggressive JS
551 * libraries like MooTools or Joomla.
552 * @param { String } str The date string, e.g. "2011/05/06"
553 * @return { Integer } millis since epoch
554 */
555 Dygraph.dateStrToMillis = function(str) {
556 return new Date(str).getTime();
557 };
558
559 // These functions are all based on MochiKit.
560 /**
561 * Copies all the properties from o to self.
562 *
563 * @private
564 */
565 Dygraph.update = function (self, o) {
566 if (typeof(o) != 'undefined' && o !== null) {
567 for (var k in o) {
568 if (o.hasOwnProperty(k)) {
569 self[k] = o[k];
570 }
571 }
572 }
573 return self;
574 };
575
576 /**
577 * Copies all the properties from o to self.
578 *
579 * @private
580 */
581 Dygraph.updateDeep = function (self, o) {
582 // Taken from http://stackoverflow.com/questions/384286/javascript-isdom-how-do-you-check-if-a-javascript-object-is-a-dom-object
583 function isNode(o) {
584 return (
585 typeof Node === "object" ? o instanceof Node :
586 typeof o === "object" && typeof o.nodeType === "number" && typeof o.nodeName==="string"
587 );
588 }
589
590 if (typeof(o) != 'undefined' && o !== null) {
591 for (var k in o) {
592 if (o.hasOwnProperty(k)) {
593 if (o[k] === null) {
594 self[k] = null;
595 } else if (Dygraph.isArrayLike(o[k])) {
596 self[k] = o[k].slice();
597 } else if (isNode(o[k])) {
598 // DOM objects are shallowly-copied.
599 self[k] = o[k];
600 } else if (typeof(o[k]) == 'object') {
601 if (typeof(self[k]) != 'object' || self[k] === null) {
602 self[k] = {};
603 }
604 Dygraph.updateDeep(self[k], o[k]);
605 } else {
606 self[k] = o[k];
607 }
608 }
609 }
610 }
611 return self;
612 };
613
614 /**
615 * @private
616 */
617 Dygraph.isArrayLike = function (o) {
618 var typ = typeof(o);
619 if (
620 (typ != 'object' && !(typ == 'function' &&
621 typeof(o.item) == 'function')) ||
622 o === null ||
623 typeof(o.length) != 'number' ||
624 o.nodeType === 3
625 ) {
626 return false;
627 }
628 return true;
629 };
630
631 /**
632 * @private
633 */
634 Dygraph.isDateLike = function (o) {
635 if (typeof(o) != "object" || o === null ||
636 typeof(o.getTime) != 'function') {
637 return false;
638 }
639 return true;
640 };
641
642 /**
643 * Note: this only seems to work for arrays.
644 * @private
645 */
646 Dygraph.clone = function(o) {
647 // TODO(danvk): figure out how MochiKit's version works
648 var r = [];
649 for (var i = 0; i < o.length; i++) {
650 if (Dygraph.isArrayLike(o[i])) {
651 r.push(Dygraph.clone(o[i]));
652 } else {
653 r.push(o[i]);
654 }
655 }
656 return r;
657 };
658
659 /**
660 * @private
661 * Create a new canvas element. This is more complex than a simple
662 * document.createElement("canvas") because of IE and excanvas.
663 */
664 Dygraph.createCanvas = function() {
665 var canvas = document.createElement("canvas");
666
667 var isIE = (/MSIE/.test(navigator.userAgent) && !window.opera);
668 if (isIE && (typeof(G_vmlCanvasManager) != 'undefined')) {
669 canvas = G_vmlCanvasManager.initElement(canvas);
670 }
671
672 return canvas;
673 };
674
675 /**
676 * @private
677 * Checks whether the user is on an Android browser.
678 * Android does not fully support the <canvas> tag, e.g. w/r/t/ clipping.
679 */
680 Dygraph.isAndroid = function() {
681 return (/Android/).test(navigator.userAgent);
682 };
683
684 /**
685 * @private
686 * Returns a new iterator over array, between indexes start and
687 * start + length, and only returns entries that pass the accept function
688 *
689 * @param array the array to iterate over.
690 * @param start the first index to iterate over
691 * @param length the number of elements in the array to iterate over.
692 * This, along with start, defines a slice of the array, and so length
693 * doesn't imply the number of elements in the iterator when accept
694 * doesn't always accept all values.
695 * @param predicate a function that takes parameters array and idx, which
696 * returns true when the element should be returned. If omitted, all
697 * elements are accepted.
698 *
699 * TODO(konigsberg): add default vlues to start and length.
700 */
701 Dygraph.createIterator = function(array, start, length, predicate) {
702 predicate = predicate || function() { return true; };
703
704 var iter = new function() {
705 this.end_ = Math.min(array.length, start + length);
706 this.nextIdx_ = start - 1; // use -1 so initial call to advance works.
707 this.hasNext_ = true;
708 this.peek_ = null;
709 var self = this;
710
711 this.hasNext = function() {
712 return self.hasNext_;
713 }
714
715 this.next = function() {
716 if (self.hasNext_) {
717 var obj = self.peek_;
718 self.advance_();
719 return obj;
720 }
721 return null;
722 }
723 this.peek = function() {
724 return self.peek_;
725 }
726 this.advance_ = function() {
727 self.nextIdx_++;
728 while(self.nextIdx_ < self.end_) {
729 if (predicate(array, self.nextIdx_)) {
730 self.peek_ = array[self.nextIdx_];
731 return;
732 }
733 self.nextIdx_++;
734 }
735 self.hasNext_ = false;
736 self.peek_ = null;
737 }
738 };
739 iter.advance_();
740 return iter;
741 };
742
743 /**
744 * @private
745 * Call a function N times at a given interval, then call a cleanup function
746 * once. repeat_fn is called once immediately, then (times - 1) times
747 * asynchronously. If times=1, then cleanup_fn() is also called synchronously.
748 * @param repeat_fn {Function} Called repeatedly -- takes the number of calls
749 * (from 0 to times-1) as an argument.
750 * @param times {number} The number of times to call repeat_fn
751 * @param every_ms {number} Milliseconds between calls
752 * @param cleanup_fn {Function} A function to call after all repeat_fn calls.
753 * @private
754 */
755 Dygraph.repeatAndCleanup = function(repeat_fn, times, every_ms, cleanup_fn) {
756 var count = 0;
757 var start_time = new Date().getTime();
758 repeat_fn(count);
759 if (times == 1) {
760 cleanup_fn();
761 return;
762 }
763
764 (function loop() {
765 if (count >= times) return;
766 var target_time = start_time + (1 + count) * every_ms;
767 setTimeout(function() {
768 count++;
769 repeat_fn(count);
770 if (count >= times - 1) {
771 cleanup_fn();
772 } else {
773 loop();
774 }
775 }, target_time - new Date().getTime());
776 // TODO(danvk): adjust every_ms to produce evenly-timed function calls.
777 })();
778 };
779
780 /**
781 * @private
782 * This function will scan the option list and determine if they
783 * require us to recalculate the pixel positions of each point.
784 * @param { List } a list of options to check.
785 * @return { Boolean } true if the graph needs new points else false.
786 */
787 Dygraph.isPixelChangingOptionList = function(labels, attrs) {
788 // A whitelist of options that do not change pixel positions.
789 var pixelSafeOptions = {
790 'annotationClickHandler': true,
791 'annotationDblClickHandler': true,
792 'annotationMouseOutHandler': true,
793 'annotationMouseOverHandler': true,
794 'axisLabelColor': true,
795 'axisLineColor': true,
796 'axisLineWidth': true,
797 'clickCallback': true,
798 'digitsAfterDecimal': true,
799 'drawCallback': true,
800 'drawHighlightPointCallback': true,
801 'drawPoints': true,
802 'drawPointCallback': true,
803 'drawXGrid': true,
804 'drawYGrid': true,
805 'fillAlpha': true,
806 'gridLineColor': true,
807 'gridLineWidth': true,
808 'hideOverlayOnMouseOut': true,
809 'highlightCallback': true,
810 'highlightCircleSize': true,
811 'interactionModel': true,
812 'isZoomedIgnoreProgrammaticZoom': true,
813 'labelsDiv': true,
814 'labelsDivStyles': true,
815 'labelsDivWidth': true,
816 'labelsKMB': true,
817 'labelsKMG2': true,
818 'labelsSeparateLines': true,
819 'labelsShowZeroValues': true,
820 'legend': true,
821 'maxNumberWidth': true,
822 'panEdgeFraction': true,
823 'pixelsPerYLabel': true,
824 'pointClickCallback': true,
825 'pointSize': true,
826 'rangeSelectorPlotFillColor': true,
827 'rangeSelectorPlotStrokeColor': true,
828 'showLabelsOnHighlight': true,
829 'showRoller': true,
830 'sigFigs': true,
831 'strokeWidth': true,
832 'underlayCallback': true,
833 'unhighlightCallback': true,
834 'xAxisLabelFormatter': true,
835 'xTicker': true,
836 'xValueFormatter': true,
837 'yAxisLabelFormatter': true,
838 'yValueFormatter': true,
839 'zoomCallback': true
840 };
841
842 // Assume that we do not require new points.
843 // This will change to true if we actually do need new points.
844 var requiresNewPoints = false;
845
846 // Create a dictionary of series names for faster lookup.
847 // If there are no labels, then the dictionary stays empty.
848 var seriesNamesDictionary = { };
849 if (labels) {
850 for (var i = 1; i < labels.length; i++) {
851 seriesNamesDictionary[labels[i]] = true;
852 }
853 }
854
855 // Iterate through the list of updated options.
856 for (var property in attrs) {
857 // Break early if we already know we need new points from a previous option.
858 if (requiresNewPoints) {
859 break;
860 }
861 if (attrs.hasOwnProperty(property)) {
862 // Find out of this field is actually a series specific options list.
863 if (seriesNamesDictionary[property]) {
864 // This property value is a list of options for this series.
865 // If any of these sub properties are not pixel safe, set the flag.
866 for (var subProperty in attrs[property]) {
867 // Break early if we already know we need new points from a previous option.
868 if (requiresNewPoints) {
869 break;
870 }
871 if (attrs[property].hasOwnProperty(subProperty) && !pixelSafeOptions[subProperty]) {
872 requiresNewPoints = true;
873 }
874 }
875 // If this was not a series specific option list, check if its a pixel changing property.
876 } else if (!pixelSafeOptions[property]) {
877 requiresNewPoints = true;
878 }
879 }
880 }
881
882 return requiresNewPoints;
883 };
884
885 /**
886 * Compares two arrays to see if they are equal. If either parameter is not an
887 * array it will return false. Does a shallow compare
888 * Dygraph.compareArrays([[1,2], [3, 4]], [[1,2], [3,4]]) === false.
889 * @param array1 first array
890 * @param array2 second array
891 * @return True if both parameters are arrays, and contents are equal.
892 */
893 Dygraph.compareArrays = function(array1, array2) {
894 if (!Dygraph.isArrayLike(array1) || !Dygraph.isArrayLike(array2)) {
895 return false;
896 }
897 if (array1.length !== array2.length) {
898 return false;
899 }
900 for (var i = 0; i < array1.length; i++) {
901 if (array1[i] !== array2[i]) {
902 return false;
903 }
904 }
905 return true;
906 };
907
908 /**
909 * ctx: the canvas context
910 * sides: the number of sides in the shape.
911 * radius: the radius of the image.
912 * cx: center x coordate
913 * cy: center y coordinate
914 * rotationRadians: the shift of the initial angle, in radians.
915 * delta: the angle shift for each line. If missing, creates a regular
916 * polygon.
917 */
918 Dygraph.regularShape_ = function(
919 ctx, sides, radius, cx, cy, rotationRadians, delta) {
920 rotationRadians = rotationRadians ? rotationRadians : 0;
921 delta = delta ? delta : Math.PI * 2 / sides;
922
923 ctx.beginPath();
924 var first = true;
925 var initialAngle = rotationRadians;
926 var angle = initialAngle;
927
928 var computeCoordinates = function() {
929 var x = cx + (Math.sin(angle) * radius);
930 var y = cy + (-Math.cos(angle) * radius);
931 return [x, y];
932 };
933
934 var initialCoordinates = computeCoordinates();
935 var x = initialCoordinates[0];
936 var y = initialCoordinates[1];
937 ctx.moveTo(x, y);
938
939 for (var idx = 0; idx < sides; idx++) {
940 angle = (idx == sides - 1) ? initialAngle : (angle + delta);
941 var coords = computeCoordinates();
942 ctx.lineTo(coords[0], coords[1]);
943 }
944 ctx.fill();
945 ctx.stroke();
946 }
947
948 Dygraph.shapeFunction_ = function(sides, rotationRadians, delta) {
949 return function(g, name, ctx, cx, cy, color, radius) {
950 ctx.strokeStyle = color;
951 ctx.fillStyle = "white";
952 Dygraph.regularShape_(ctx, sides, radius, cx, cy, rotationRadians, delta);
953 };
954 };
955
956 Dygraph.DrawPolygon_ = function(sides, rotationRadians, ctx, cx, cy, color, radius, delta) {
957 new Dygraph.RegularShape_(sides, rotationRadians, delta).draw(ctx, cx, cy, radius);
958 }
959
960 Dygraph.Circles = {
961 DEFAULT : function(g, name, ctx, canvasx, canvasy, color, radius) {
962 ctx.beginPath();
963 ctx.fillStyle = color;
964 ctx.arc(canvasx, canvasy, radius, 0, 2 * Math.PI, false);
965 ctx.fill();
966 },
967 TRIANGLE : Dygraph.shapeFunction_(3),
968 SQUARE : Dygraph.shapeFunction_(4, Math.PI / 4),
969 DIAMOND : Dygraph.shapeFunction_(4),
970 PENTAGON : Dygraph.shapeFunction_(5),
971 HEXAGON : Dygraph.shapeFunction_(6),
972 CIRCLE : function(g, name, ctx, cx, cy, color, radius) {
973 ctx.beginPath();
974 ctx.strokeStyle = color;
975 ctx.fillStyle = "white";
976 ctx.arc(cx, cy, radius, 0, 2 * Math.PI, false);
977 ctx.fill();
978 ctx.stroke();
979 },
980 STAR : Dygraph.shapeFunction_(5, 0, 4 * Math.PI / 5),
981 PLUS : function(g, name, ctx, cx, cy, color, radius) {
982 ctx.strokeStyle = color;
983
984 ctx.beginPath();
985 ctx.moveTo(cx + radius, cy);
986 ctx.lineTo(cx - radius, cy);
987 ctx.closePath();
988 ctx.stroke();
989
990 ctx.beginPath();
991 ctx.moveTo(cx, cy + radius);
992 ctx.lineTo(cx, cy - radius);
993 ctx.closePath();
994 ctx.stroke();
995 },
996 EX : function(g, name, ctx, cx, cy, color, radius) {
997 ctx.strokeStyle = color;
998
999 ctx.beginPath();
1000 ctx.moveTo(cx + radius, cy + radius);
1001 ctx.lineTo(cx - radius, cy - radius);
1002 ctx.closePath();
1003 ctx.stroke();
1004
1005 ctx.beginPath();
1006 ctx.moveTo(cx + radius, cy - radius);
1007 ctx.lineTo(cx - radius, cy + radius);
1008 ctx.closePath();
1009 ctx.stroke();
1010 }
1011 };