Skip to content

Commit

Permalink
feat: pow refactor wip
Browse files Browse the repository at this point in the history
  • Loading branch information
martonlederer committed Apr 14, 2024
1 parent 8ae7a87 commit 7699b5f
Showing 1 changed file with 22 additions and 7 deletions.
29 changes: 22 additions & 7 deletions src/Quantity.ts
Original file line number Diff line number Diff line change
Expand Up @@ -477,16 +477,31 @@ export default class Quantity {
}

/**
* Raise one quantity to the power of an integer. This can cause precision loss
* Raise one quantity to the power of another. This can cause precision loss
* @param x Quantity to raise
* @param y Exponent
* @returns Result of the power operation
*/
static __pow(x: Quantity, y: number) {
if (!Number.isInteger(y)) {
throw new Error("Cannot raise Quantity to the power of a non-integer number");
static __pow(x: Quantity, y: Quantity | bigint) {
if (typeof y !== "bigint" && !Quantity.isQuantity(y)) {
throw new Error("Invalid exponent");
}
if (y === 0) return new Quantity(0, x.#D);

// power of 0
if ((typeof y === "bigint" && y === 0n) || Quantity.isQuantity(y) && Quantity.eq(y, new Quantity(0n, y.#D))) {
return Quantity.__one(x.#D);
}

// integer power
if (typeof y === "bigint") {
return new Quantity(
x.#qty ** y,
x.#D ** y
)._convert(x.#D);
}

// ensure same denomination
[x, y] = Quantity.sameDenomination(x, y);

let res = x.clone();

Expand All @@ -506,11 +521,11 @@ export default class Quantity {
}

/**
* Raise one quantity to the power of an integer (in-place). This can cause
* Raise one quantity to the power of another (in-place). This can cause
* precision loss
* @param y Exponent
*/
_pow(y: number) {
_pow(y: Quantity | bigint) {
const res = Quantity.__convert(
Quantity.__pow(this, y),
this.#D
Expand Down

0 comments on commit 7699b5f

Please sign in to comment.