3 * Copyright 2015 Petr Shevtsov (petr.shevtsov@gmail.com)
4 * MIT-licensed (http://opensource.org/licenses/MIT)
8 * On pan/zoom event, each series will rebase to a specified value (e.g. 100) at the
9 * start of the displayed period.
11 * See http://stats.oecd.org/glossary/detail.asp?ID=2249
14 * Value to rebase. Must be either Number or 'percent' or null.
16 * See tests/straw-broom.html for demo.
19 /*global Dygraph:false */
25 // Matches DefaultHandler.parseFloat
26 var parseFloat
= function(val
) {
27 if (val
=== null) return NaN
;
31 Dygraph
.DataHandlers
.RebaseHandler
= function(baseOpt
) {
32 this.baseOpt
= baseOpt
;
35 var RebaseHandler
= Dygraph
.DataHandlers
.RebaseHandler
;
36 RebaseHandler
.prototype = new Dygraph
.DataHandlers
.DefaultHandler();
38 RebaseHandler
.rebase
= function(value
, initial
, base
) {
39 if (base
=== "percent") {
40 return (value
/ initial
- 1) * 100;
42 return value
* base
/ initial
;
45 RebaseHandler
.prototype.getExtremeYValues
= function(series
, dateWindow
, options
) {
46 var minY
= null, maxY
= null, y
;
47 var firstIdx
= 0, lastIdx
= series
.length
- 1;
48 var initial
= series
[firstIdx
][1];
50 for (var j
= firstIdx
; j
<= lastIdx
; j
++) {
52 y
= (this.baseOpt
=== "percent") ? 0 : this.baseOpt
;
54 y
= RebaseHandler
.rebase(series
[j
][1], initial
, this.baseOpt
);
56 if (y
=== null || isNaN(y
))
58 if (maxY
=== null || y
> maxY
) {
61 if (minY
=== null || y
< minY
) {
65 return [ minY
, maxY
];
68 RebaseHandler
.prototype.seriesToPoints
= function(series
, setName
, boundaryIdStart
){
71 var lastIdx
= series
.length
- 1;
72 var initial
= series
[firstIdx
][1]; // TODO: check for null
73 for (var i
= 0; i
<= lastIdx
; ++i
) {
76 var yval
= yraw
=== null ? null : parseFloat(yraw
);
79 yval
= (this.baseOpt
=== "percent") ? 0 : this.baseOpt
;
81 yval
= RebaseHandler
.rebase(yval
, initial
, this.baseOpt
);
87 xval
: parseFloat(item
[0]),
90 idx
: i
+ boundaryIdStart
94 this.onPointsCreated_(series
, points
);
98 Dygraph
.Plugins
.Rebase
= (function() {
99 var rebase
= function(baseOpt
) {
100 var isNum
= function(v
) {
101 return !isNaN(v
) && (typeof v
=== 'number' || {}.toString
.call(v
) === '[object Number]');
103 if (baseOpt
=== "percent" || isNum(baseOpt
)) {
104 this.baseOpt_
= baseOpt
;
106 this.baseOpt_
= null;
110 rebase
.prototype.toString
= function() {
111 return "Rebase Plugin";
114 rebase
.prototype.activate
= function(g
) {
115 if (this.baseOpt_
=== null) {
119 predraw
: this.predraw
123 rebase
.prototype.predraw
= function(e
) {
126 if (this.baseOpt_
=== "percent") {
130 axisLabelFormatter
: function(y
) {
133 valueFormatter
: function(y
) {
134 return Math
.round(y
* 100) / 100 + '%';
141 g
.dataHandler_
= new Dygraph
.DataHandlers
.RebaseHandler(this.baseOpt_
);