From 3d4adb6b044ff1361a970ea049f90d5626ea9888 Mon Sep 17 00:00:00 2001 From: Bogdan Chadkin Date: Mon, 22 Mar 2021 14:38:06 +0300 Subject: [PATCH] Simplify number rendering and fix -0 in path Ref https://github.com/svg/svgo/issues/1422 --- lib/path.js | 16 ++++------------ lib/path.test.js | 22 ++++++++++------------ test/plugins/convertPathData.17.svg | 2 +- test/plugins/convertShapeToPath.05.svg | 2 +- 4 files changed, 16 insertions(+), 26 deletions(-) diff --git a/lib/path.js b/lib/path.js index ef1a3e114..f8d4822b1 100644 --- a/lib/path.js +++ b/lib/path.js @@ -241,20 +241,12 @@ exports.parsePathData = parsePathData; * @param {StringifyNumberOptions} param */ const stringifyNumber = ({ number, precision }) => { - let result; - if (precision == null) { - result = number.toString(); - } else { - result = number.toFixed(precision); - if (result.includes('.')) { - result = result.replace(/\.?0+$/, ''); - } + if (precision != null) { + const ratio = 10 ** precision; + number = Math.round(number * ratio) / ratio; } // remove zero whole from decimal number - if (result !== '0') { - result = result.replace(/^0/, '').replace(/^-0/, '-'); - } - return result; + return number.toString().replace(/^0\./, '.').replace(/^-0\./, '-.'); }; /** diff --git a/lib/path.test.js b/lib/path.test.js index 8268a7319..879b8f93a 100644 --- a/lib/path.test.js +++ b/lib/path.test.js @@ -142,26 +142,24 @@ describe('stringify path data', () => { ).to.equal('M0-1.2.3 4 5-.6 7 .8'); }); it('should configure precision', () => { + const pathData = [ + { command: 'M', args: [0, -1.9876] }, + { command: 'L', args: [0.3, 3.14159265] }, + { command: 'L', args: [-0.3, -3.14159265] }, + { command: 'L', args: [100, 200] }, + ]; expect( stringifyPathData({ - pathData: [ - { command: 'M', args: [0, -1.9876] }, - { command: 'L', args: [0.3, 3.14159265] }, - { command: 'L', args: [100, 200] }, - ], + pathData, precision: 3, }) - ).to.equal('M0-1.988.3 3.142 100 200'); + ).to.equal('M0-1.988.3 3.142-.3-3.142 100 200'); expect( stringifyPathData({ - pathData: [ - { command: 'M', args: [0, -1.9876] }, - { command: 'L', args: [0.3, 3.14159265] }, - { command: 'L', args: [100, 200] }, - ], + pathData, precision: 0, }) - ).to.equal('M0-2 0 3 100 200'); + ).to.equal('M0-2 0 3 0-3 100 200'); }); it('allows to avoid spaces after arc flags', () => { const pathData = [ diff --git a/test/plugins/convertPathData.17.svg b/test/plugins/convertPathData.17.svg index 3e4a87420..e6ddb6839 100644 --- a/test/plugins/convertPathData.17.svg +++ b/test/plugins/convertPathData.17.svg @@ -5,7 +5,7 @@ @@@ - + @@@ diff --git a/test/plugins/convertShapeToPath.05.svg b/test/plugins/convertShapeToPath.05.svg index 054905e2a..6f528646d 100644 --- a/test/plugins/convertShapeToPath.05.svg +++ b/test/plugins/convertShapeToPath.05.svg @@ -19,7 +19,7 @@ Precision should be applied to all converted shapes - + @@@