Skip to content

Commit

Permalink
Added toString to Density.
Browse files Browse the repository at this point in the history
  • Loading branch information
dlemstra committed Oct 25, 2024
1 parent 930167c commit 6798a37
Show file tree
Hide file tree
Showing 2 changed files with 60 additions and 0 deletions.
26 changes: 26 additions & 0 deletions src/types/density.ts
Original file line number Diff line number Diff line change
Expand Up @@ -57,4 +57,30 @@ export class Density {
* Gets the units.
*/
readonly units: DensityUnit;

/**
* Returns a string that represents the current {@link Density} object.
*/
toString(units?: DensityUnit): string {
if (units == this.units || units === DensityUnit.Undefined || units === undefined)
return Density.toString(this.x, this.y, units ?? DensityUnit.Undefined);
else if (this.units == DensityUnit.PixelsPerCentimeter && units == DensityUnit.PixelsPerInch)
return Density.toString(this.x * 2.54, this.y * 2.54, units);
else
return Density.toString(this.x / 2.54, this.y / 2.54, units);
}

private static toString(x: number, y: number, units: DensityUnit): string {
let result = `${x}x${y}`;
switch (units) {
case DensityUnit.PixelsPerCentimeter:
result += 'cm';
break;
case DensityUnit.PixelsPerInch:
result += 'inch';
break;
}

return result;
}
}
34 changes: 34 additions & 0 deletions tests/types/density/to-string.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
/*
Copyright Dirk Lemstra https://github.com/dlemstra/magick-wasm.
Licensed under the Apache License, Version 2.0.
*/

import { Density } from '@src/types/density';
import { DensityUnit } from '@src/enums/density-unit';

describe('Density#toString', () => {
it('should use undefined density units by default', () => {
const density = new Density(4, 2, DensityUnit.PixelsPerCentimeter);
expect(density.toString()).toBe('4x2');
});

it('should add cm when density unit matches', () => {
const density = new Density(4, 2, DensityUnit.PixelsPerCentimeter);
expect(density.toString(DensityUnit.PixelsPerCentimeter)).toBe('4x2cm');
});

it('should add inch when density unit matches', () => {
const density = new Density(4, 2, DensityUnit.PixelsPerInch);
expect(density.toString(DensityUnit.PixelsPerInch)).toBe('4x2inch');
});

it('should convert cm to inch', () => {
const density = new Density(4, 2, DensityUnit.PixelsPerCentimeter);
expect(density.toString(DensityUnit.PixelsPerInch)).toBe('10.16x5.08inch');
});

it('should convert inch to cm', () => {
const density = new Density(4, 2, DensityUnit.PixelsPerInch);
expect(density.toString(DensityUnit.PixelsPerCentimeter)).toBe('1.574803149606299x0.7874015748031495cm');
});
});

0 comments on commit 6798a37

Please sign in to comment.