Skip to content

Commit

Permalink
Update formatting logic in IITC.utils.formatDistance
Browse files Browse the repository at this point in the history
  • Loading branch information
modos189 committed Oct 31, 2024
1 parent c171353 commit d5467eb
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 8 deletions.
27 changes: 23 additions & 4 deletions core/code/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -190,7 +190,13 @@ const formatInterval = (seconds, maxTerms) => {
};

/**
* Formats a distance in meters, converting to kilometers if the distance is over 10,000 meters.
* Formats a distance in meters, converting to kilometers with appropriate precision
* based on the distance range.
*
* For distances:
* - Under 1000m: shows in meters, rounded to whole numbers
* - 1000m to 9999m: shows in kilometers with 1 decimal place
* - 10000m and above: shows in whole kilometers
*
* @memberof IITC.utils
* @function formatDistance
Expand All @@ -199,9 +205,22 @@ const formatInterval = (seconds, maxTerms) => {
*/
const formatDistance = (distance) => {
if (distance === null || distance === undefined) return '';
const isKilometers = distance > 10000;
const value = isKilometers ? (distance / 1000).toFixed(2) : Math.round(distance);
const unit = isKilometers ? 'km' : 'm';
let value, unit;

if (distance >= 10000) {
// For 10km and above: show whole kilometers
value = Math.round(distance / 1000);
unit = 'km';
} else if (distance >= 1000) {
// For 1km to 9.9km: show kilometers with one decimal
value = Math.round(distance / 100) / 10;
unit = 'km';
} else {
// For under 1km: show in meters
value = Math.round(distance);
unit = 'm';
}

return `${IITC.utils.formatNumber(value)}${unit}`;
};

Expand Down
8 changes: 4 additions & 4 deletions test/utils.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -325,17 +325,17 @@ describe('IITC.utils.formatDistance', () => {

it('should format distance in kilometers with two decimal places if above 10 000 meters', () => {
const result = IITC.utils.formatDistance(12345); // 12.35 kilometers
expect(result).to.equal('12.35km');
expect(result).to.equal('12km');
});

it('should format exactly 10 000 meters in meters, not kilometers', () => {
it('should format exactly 10 kilometers, not 10 000 meters', () => {
const result = IITC.utils.formatDistance(10000); // 10 000 meters
expect(result).to.equal('10\u2009000m');
expect(result).to.equal('10km');
});

it('should format large distances in kilometers with two decimal places', () => {
const result = IITC.utils.formatDistance(987654); // 987.65 kilometers
expect(result).to.equal('987.65km');
expect(result).to.equal('988km');
});

it('should handle zero distance as "0m"', () => {
Expand Down

0 comments on commit d5467eb

Please sign in to comment.