Fix bug when calculating if steps fit into scale as a whole number then smal floating point errors make the consition pass false

This commit is contained in:
Tarqwyn 2016-12-06 14:43:29 +00:00 committed by Evert Timberg
parent 6f40d04964
commit 34d26ea497
3 changed files with 11 additions and 2 deletions

View File

@ -237,6 +237,10 @@ module.exports = function(Chart) {
helpers.almostEquals = function(x, y, epsilon) {
return Math.abs(x - y) < epsilon;
};
helpers.almostWhole = function(x, epsilon) {
var rounded = Math.round(x);
return (((rounded - epsilon) < x) && ((rounded + epsilon) > x));
};
helpers.max = function(array) {
return array.reduce(function(max, value) {
if (!isNaN(value)) {

View File

@ -67,8 +67,8 @@ module.exports = function(Chart) {
// If min, max and stepSize is set and they make an evenly spaced scale use it.
if (generationOptions.min && generationOptions.max && generationOptions.stepSize) {
var minMaxDeltaDivisibleByStepSize = ((generationOptions.max - generationOptions.min) % generationOptions.stepSize) === 0;
if (minMaxDeltaDivisibleByStepSize) {
// If very close to our whole number, use it.
if (helpers.almostWhole((generationOptions.max - generationOptions.min) / generationOptions.stepSize, spacing / 1000)) {
niceMin = generationOptions.min;
niceMax = generationOptions.max;
}

View File

@ -301,6 +301,11 @@ describe('Core helper tests', function() {
expect(helpers.almostEquals(1e30, 1e30 + Number.EPSILON, 2 * Number.EPSILON)).toBe(true);
});
it('should correctly determine if a numbers are essentially whole', function() {
expect(helpers.almostWhole(0.99999, 0.0001)).toBe(true);
expect(helpers.almostWhole(0.9, 0.0001)).toBe(false);
});
it('should generate integer ids', function() {
var uid = helpers.uid();
expect(uid).toEqual(jasmine.any(Number));