Skip to content

Commit 916bf80

Browse files
committed
add incrementNumeric to Lib make it reusable and testable
force magic number to be positive to avoid getting -0
1 parent 740574b commit 916bf80

File tree

3 files changed

+40
-21
lines changed

3 files changed

+40
-21
lines changed

src/lib/increment_numeric.js

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
/**
2+
* Copyright 2012-2019, Plotly, Inc.
3+
* All rights reserved.
4+
*
5+
* This source code is licensed under the MIT license found in the
6+
* LICENSE file in the root directory of this source tree.
7+
*/
8+
9+
10+
'use strict';
11+
12+
module.exports = function incrementNumeric(x, delta) {
13+
if(!delta) return x;
14+
15+
// Note 1:
16+
// 0.3 != 0.1 + 0.2 == 0.30000000000000004
17+
// but 0.3 == (10 * 0.1 + 10 * 0.2) / 10
18+
// Attempt to use integer steps to increment
19+
var magic = 1 / Math.abs(delta);
20+
var newX = (
21+
magic * x +
22+
magic * delta
23+
) / magic;
24+
25+
// Note 2:
26+
// now we may also consider rounding to cover few more edge cases
27+
// e.g. 0.3 * 3 = 0.8999999999999999
28+
var lenDt = ('' + delta).length;
29+
var lenX0 = ('' + x).length;
30+
var lenX1 = ('' + newX).length;
31+
32+
if(lenX1 > lenX0 + lenDt) { // likely a rounding error!
33+
newX = +parseFloat(newX).toPrecision(12);
34+
}
35+
36+
return newX;
37+
};

src/lib/index.js

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -149,6 +149,8 @@ lib.clearResponsive = require('./clear_responsive');
149149

150150
lib.makeTraceGroups = require('./make_trace_groups');
151151

152+
lib.incrementNumeric = require('./increment_numeric');
153+
152154
lib._ = require('./localize');
153155

154156
lib.notifier = require('./notifier');

src/plots/cartesian/axes.js

Lines changed: 1 addition & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -847,27 +847,7 @@ axes.tickIncrement = function(x, dtick, axrev, calendar) {
847847
var axSign = axrev ? -1 : 1;
848848

849849
// includes linear, all dates smaller than month, and pure 10^n in log
850-
if(isNumeric(dtick)) {
851-
// Note 1:
852-
// 0.3 != 0.1 + 0.2 but 0.3 == ((10 * 0.1) + (10 * 0.2)) / 10
853-
// Attempt to use integer steps to increment
854-
var magic = 1 / dtick;
855-
var newX = (
856-
magic * x +
857-
magic * axSign * dtick
858-
) / magic;
859-
860-
// Note 2: now we may also consider rounding to cover few more edge cases
861-
var lenDt = ('' + dtick).length;
862-
var lenX0 = ('' + x).length;
863-
var lenX1 = ('' + newX).length;
864-
865-
if(lenX1 > lenX0 + lenDt) { // this is likey a rounding error!
866-
newX = +parseFloat(newX).toPrecision(12);
867-
}
868-
869-
return newX;
870-
}
850+
if(isNumeric(dtick)) return Lib.incrementNumeric(x, axSign * dtick);
871851

872852
// everything else is a string, one character plus a number
873853
var tType = dtick.charAt(0);

0 commit comments

Comments
 (0)