Skip to content

Commit

Permalink
Simplify number rendering and fix -0 in path
Browse files Browse the repository at this point in the history
Ref #1422
  • Loading branch information
TrySound committed Mar 22, 2021
1 parent 316a002 commit 3d4adb6
Show file tree
Hide file tree
Showing 4 changed files with 16 additions and 26 deletions.
16 changes: 4 additions & 12 deletions lib/path.js
Original file line number Diff line number Diff line change
Expand Up @@ -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\./, '-.');
};

/**
Expand Down
22 changes: 10 additions & 12 deletions lib/path.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -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 = [
Expand Down
2 changes: 1 addition & 1 deletion test/plugins/convertPathData.17.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
2 changes: 1 addition & 1 deletion test/plugins/convertShapeToPath.05.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.

0 comments on commit 3d4adb6

Please sign in to comment.