Skip to content

Commit

Permalink
chore: minor cleanups to Dimensions
Browse files Browse the repository at this point in the history
  • Loading branch information
bradenmacdonald committed Mar 12, 2024
1 parent 400aeab commit 2841b0c
Showing 1 changed file with 10 additions and 20 deletions.
30 changes: 10 additions & 20 deletions dimensions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,9 +52,7 @@ export class Dimensions {
] = [],
) {
if (dimensions.length < numBasicDimensions) {
throw new QuantityError(
"not enough dimensions specified for Quantity.",
);
throw new QuantityError("not enough dimensions specified for Quantity.");
}

const numCustomDimensions = customDimensionNames.length;
Expand All @@ -64,28 +62,23 @@ export class Dimensions {
);
}

if (customDimensionNames.length) {
if (numCustomDimensions) {
// Make sure customDimensionNames is sorted in alphabetical order, for consistency.
// This also validated that there are no duplicate custom dimensions (["floop", "floop"])
const isSorted = customDimensionNames.every((
v,
i,
a,
) => (i === 0 || v! > a[i - 1]!));
const isSorted = customDimensionNames.every((v, i, a) => (i === 0 || v! > a[i - 1]!));
if (!isSorted) {
throw new QuantityError(
"customDimensionNames is not sorted into the correct alphabetical order.",
);
throw new QuantityError("customDimensionNames is not sorted into the correct alphabetical order.");
}
}
}

/** Is this dimensionless? (all dimensions are zero) */
public get isDimensionless(): boolean {
return this === Dimensionless || this.dimensions.every((d) => d === 0);
if (this.#cachedDimensionality !== undefined) return this.#cachedDimensionality === 0;
return this.dimensions.every((d) => d === 0);
}

/** Private cache of the dimensionality, as a minor optimization */
/** Private cache of the dimensionality, as an optimization */
#cachedDimensionality: number | undefined;

/** Get the dimensionality of this - the sum of the absolute values of all dimensions */
Expand Down Expand Up @@ -180,18 +173,15 @@ export class Dimensions {

/** Raise these dimensions to a power */
public pow(n: number): Dimensions {
if (typeof n !== "number" || isNaN(n) || !Number.isInteger(n)) {
if (!Number.isInteger(n)) {
throw new QuantityError(`Dimensions.pow(n): n must be an integer`);
}
if (n === 0) {
return Dimensionless;
}
const newDimArray = this.dimensions.map((d) => d! * n);
return new Dimensions(
// deno-lint-ignore no-explicit-any
newDimArray as any,
this.customDimensionNames,
);
// deno-lint-ignore no-explicit-any
return new Dimensions(newDimArray as any, this.customDimensionNames);
}

/** Use a nice string when logging this with Deno's console.log() etc. */
Expand Down

0 comments on commit 2841b0c

Please sign in to comment.