Skip to content

Commit

Permalink
Refactor measure formatting (#73)
Browse files Browse the repository at this point in the history
  • Loading branch information
jscheiny authored Nov 1, 2018
1 parent aac30ff commit b835b5b
Showing 1 changed file with 13 additions and 25 deletions.
38 changes: 13 additions & 25 deletions src/measure/format.ts
Original file line number Diff line number Diff line change
@@ -1,35 +1,23 @@
import { SymbolAndExponent, UnitWithSymbols } from "./unitTypeArithmetic";

export function formatUnit(unit: UnitWithSymbols): string {
const sorted = sortDimensions(unit);
if (sorted.length === 0) {
return "";
}
const formatted = Object.keys(unit)
.map(dimension => unit[dimension])
.filter(isDimensionPresent)
.sort(orderDimensions)
.map(formatDimension);
return formatted.length === 0 ? "" : " " + formatted.join(" * ");
}

return " " + sorted.map(formatDimension).join(" * ");
function isDimensionPresent(dimension: SymbolAndExponent | undefined): dimension is SymbolAndExponent {
return dimension !== undefined && dimension[1] !== 0;
}

function sortDimensions(unit: UnitWithSymbols): SymbolAndExponent[] {
const dimensions: SymbolAndExponent[] = [];
for (const dimension in unit) {
const symbolAndExponent = unit[dimension];
if (symbolAndExponent === undefined) {
continue;
}
const [, exponent] = symbolAndExponent;
if (exponent !== 0) {
dimensions.push(symbolAndExponent);
}
function orderDimensions([leftSymbol]: SymbolAndExponent, [rightSymbol]: SymbolAndExponent): number {
if (leftSymbol < rightSymbol) {
return -1;
}

dimensions.sort(([leftSymbol], [rightSymbol]) => {
if (leftSymbol < rightSymbol) {
return -1;
}
return 1;
});

return dimensions;
return 1;
}

function formatDimension([symbol, exponent]: SymbolAndExponent): string {
Expand Down

0 comments on commit b835b5b

Please sign in to comment.