Skip to content

Commit

Permalink
Fast version
Browse files Browse the repository at this point in the history
  • Loading branch information
evert committed Aug 1, 2020
1 parent edb7139 commit a0253c8
Showing 1 changed file with 11 additions and 7 deletions.
18 changes: 11 additions & 7 deletions src/money.ts
Original file line number Diff line number Diff line change
Expand Up @@ -115,19 +115,23 @@ export class Money {
*
* pow currently only supports whole numbers.
*/
pow(exponent: number): Money {
pow(exponent: number | bigint): Money {

if (!Number.isInteger(exponent)) {
if (typeof exponent === 'number' && !Number.isInteger(exponent)) {
throw new Error('You can currently only use pow() with whole numbers');
}

if (exponent > 1) {
let base:Money = this;
for(let i = 1; i < exponent; i++) {
base = base.multiply(this);
}
return base;
const resultBig = this.value ** BigInt(exponent);
return Money.fromSource(
divide(resultBig, PRECISION_M ** (BigInt(exponent)-1n), this.round),
this.currency,
this.round
);
} else {
// This handles the 0, 1 and negative exponent cases.
// This uses an iterative approach and is therefore not going to super
// fast.
let base:Money = this;
for(let i = 1; i > exponent; i--) {
base = base.divide(this);
Expand Down

0 comments on commit a0253c8

Please sign in to comment.