]> git.ipfire.org Git - thirdparty/Chart.js.git/commitdiff
Write an almost equals function and use it in the linear scale. Added a test for... 1984/head
authorEvert Timberg <evert.timberg@gmail.com>
Sat, 6 Feb 2016 14:38:44 +0000 (09:38 -0500)
committerEvert Timberg <evert.timberg@gmail.com>
Sat, 6 Feb 2016 14:38:44 +0000 (09:38 -0500)
src/core/core.helpers.js
src/scales/scale.linear.js
test/core.helpers.tests.js

index 65bdd130472b30ed2ddc27e897f818023e067939..d61b9bc82a8359b971413d0431ab05d9839c7bfb 100644 (file)
        helpers.isNumber = function(n) {
                return !isNaN(parseFloat(n)) && isFinite(n);
        };
+       helpers.almostEquals = function(x, y, epsilon) {
+               return Math.abs(x - y) < epsilon;
+       };
        helpers.max = function(array) {
                return array.reduce(function(max, value) {
                        if (!isNaN(value)) {
index 334e999ebac9635400efaa056e7a3303d0ec6ffb..e934f3c83cf45c70e84e8763d2219e2ca87a931f 100644 (file)
                        var niceMin = Math.floor(this.min / spacing) * spacing;
                        var niceMax = Math.ceil(this.max / spacing) * spacing;
 
-                       var numSpaces = Math.ceil((niceMax - niceMin) / spacing);
+                       var numSpaces = (niceMax - niceMin) / spacing;
+                       // If very close to our rounded value, use it. 
+                       if (helpers.almostEquals(numSpaces, Math.round(numSpaces), spacing / 1000)) {
+                               numSpaces = Math.round(numSpaces);
+                       } else {
+                               numSpaces = Math.ceil(numSpaces);
+                       }
 
                        // Put the values into the ticks array
                        this.ticks.push(this.options.ticks.min !== undefined ? this.options.ticks.min : niceMin);
index 224cc83f2b768c12f8da1bdccd8fd368e7bf0048..2d03289ff74f00a9b5861b0db40f59873be72e04 100644 (file)
@@ -329,6 +329,13 @@ describe('Core helper tests', function() {
                expect(helpers.log10(1000)).toBeCloseTo(3, 1e-9);
        });
 
+       it('should correctly determine if two numbers are essentially equal', function() {
+               expect(helpers.almostEquals(0, Number.EPSILON, 2 * Number.EPSILON)).toBe(true);
+               expect(helpers.almostEquals(1, 1.1, 0.0001)).toBe(false);
+               expect(helpers.almostEquals(1e30, 1e30 + Number.EPSILON, 0)).toBe(false);
+               expect(helpers.almostEquals(1e30, 1e30 + Number.EPSILON, 2 * Number.EPSILON)).toBe(true);
+       });
+
        it('Should generate ids', function() {
                expect(helpers.uid()).toBe('chart-0');
                expect(helpers.uid()).toBe('chart-1');