]> git.ipfire.org Git - thirdparty/Chart.js.git/commitdiff
Bugfix: Improve polyfill function of log10 to return whole powers of 10 (#5275)
authorjcopperfield <33193571+jcopperfield@users.noreply.github.com>
Tue, 20 Feb 2018 23:44:01 +0000 (00:44 +0100)
committerEvert Timberg <evert.timberg+github@gmail.com>
Tue, 20 Feb 2018 23:44:01 +0000 (18:44 -0500)
* Bugfix: Improve polyfill function of log10 to return whole powers of 10
        as integer values, as it caused endless loop in IE11 in the tick
        creation loop.

* Compare floating-point numbers directly instead of using unnecessary division.

src/core/core.helpers.js
test/specs/core.helpers.tests.js

index bdce895cf707b90dd5545b678d441f1b0958796b..347fd958e8386fc907338ba50be915a2a556312f 100644 (file)
@@ -159,7 +159,13 @@ module.exports = function(Chart) {
                        return Math.log10(x);
                } :
                function(x) {
-                       return Math.log(x) / Math.LN10;
+                       var exponent = Math.log(x) * Math.LOG10E; // Math.LOG10E = 1 / Math.LN10.
+                       // Check for whole powers of 10,
+                       // which due to floating point rounding error should be corrected.
+                       var powerOf10 = Math.round(exponent);
+                       var isPowerOf10 = x === Math.pow(10, powerOf10);
+
+                       return isPowerOf10 ? powerOf10 : exponent;
                };
        helpers.toRadians = function(degrees) {
                return degrees * (Math.PI / 180);
index 44446d38ab85649c9a9dd023faa117f4371cee1c..eb96ef8c745bc55c84198d623bf33aa316f9275a 100644 (file)
@@ -194,8 +194,12 @@ describe('Core helper tests', function() {
 
        it('should do a log10 operation', function() {
                expect(helpers.log10(0)).toBe(-Infinity);
-               expect(helpers.log10(1)).toBe(0);
-               expect(helpers.log10(1000)).toBeCloseTo(3, 1e-9);
+
+               // Check all allowed powers of 10, which should return integer values
+               var maxPowerOf10 = Math.floor(helpers.log10(Number.MAX_VALUE));
+               for (var i = 0; i < maxPowerOf10; i += 1) {
+                       expect(helpers.log10(Math.pow(10, i))).toBe(i);
+               }
        });
 
        it('should correctly determine if two numbers are essentially equal', function() {