Skip to content

Commit

Permalink
Add valueIn method (#185)
Browse files Browse the repository at this point in the history
  • Loading branch information
jscheiny authored May 17, 2024
1 parent 5185d1c commit 65cbe11
Show file tree
Hide file tree
Showing 6 changed files with 24 additions and 0 deletions.
6 changes: 6 additions & 0 deletions src/measure/__test__/numberMeasureTests.ts
Original file line number Diff line number Diff line change
Expand Up @@ -287,6 +287,12 @@ describe("Number measures", () => {
expect(Measure.of(1000, meters).in(kilometers)).toBe("1000 m");
});

it("should get value in another unit", () => {
const kilometers = Measure.of(1000, meters);
expect(Measure.of(2000, meters).valueIn(kilometers)).toBe(2);
expect(Measure.of(500, meters).valueIn(kilometers)).toBe(0.5);
});

it("should use base unit symbols to format when available", () => {
const m = Measure.dimension("test-length", "meter");
const s = Measure.dimension("test-time", "second");
Expand Down
8 changes: 8 additions & 0 deletions src/measure/genericMeasure.ts
Original file line number Diff line number Diff line change
Expand Up @@ -193,6 +193,14 @@ export interface GenericMeasure<N, U extends Unit> {
*/
in(unit: GenericMeasure<N, U>, formatter?: MeasureFormatter<N>): string;

/**
* Returns the value of this measure as a product of another unit. This can be used to quickly convert a measure to
* that unit and extract its underlying value.
* @param unit a measure of the same unit to convert this measure into
* @returns the numeric value of this unit expressed in the given unit
*/
valueIn(unit: GenericMeasure<N, U>): N;

/**
* Adds a symbol to this measure.
* @param symbol the symbol of the unit represented by this measure
Expand Down
4 changes: 4 additions & 0 deletions src/measure/genericMeasureClass.ts
Original file line number Diff line number Diff line change
Expand Up @@ -147,6 +147,10 @@ export function createMeasureClass<N>(num: NumericOperations<N>): GenericMeasure
return `${value} ${unit.symbol}`;
}

public valueIn(unit: GenericMeasure<N, U>): N {
return num.div(this.value, unit.value);
}

public withSymbol(symbol: string | undefined): GenericMeasure<N, U> {
return new Measure(this.value, this.unit, symbol);
}
Expand Down
File renamed without changes.
6 changes: 6 additions & 0 deletions test/measures.ts β†’ test/measureTypeTests.ts
Original file line number Diff line number Diff line change
Expand Up @@ -58,3 +58,9 @@ area.minus(volume);

// TODO(jscheinerman): This should be an error but is not because of structural typing
length.plus(velocity);

// TODO(jscheinerman): This should be an error but is not because of structural typing
length.valueIn(velocity);

// TODO(jscheinerman): This should be an error but is not because of structural typing
export const test: Length = velocity;
File renamed without changes.

0 comments on commit 65cbe11

Please sign in to comment.