Skip to content

Commit

Permalink
Merge pull request #37 from evert/pow
Browse files Browse the repository at this point in the history
POW operation.
  • Loading branch information
evert authored Aug 1, 2020
2 parents 8214d1b + fb9649a commit 3211836
Show file tree
Hide file tree
Showing 5 changed files with 68 additions and 2 deletions.
5 changes: 3 additions & 2 deletions .eslintrc.json
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@
"ts-expect-error": "allow-with-description"
}
],
"@typescript-eslint/no-explicit-any" : 0
"@typescript-eslint/no-explicit-any" : 0,
"@typescript-eslint/no-this-alias": 0
}
}
}
6 changes: 6 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,12 @@
Changelog
=========

1.2.0 (2020-08-01)
------------------

* Added `pow()` operation.


1.1.1 (2020-02-02)
------------------

Expand Down
3 changes: 3 additions & 0 deletions readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -118,6 +118,9 @@ const result = new Money(10).divide(3);

// Multiplication
const result = new Money('2000').multiply('1.25');

// Powers
const result = new Money(2).pow(8);
```

### Comparing objects
Expand Down
31 changes: 31 additions & 0 deletions src/money.ts
Original file line number Diff line number Diff line change
Expand Up @@ -110,6 +110,37 @@ export class Money {

}

/**
* Pow returns the current value to it's exponent.
*
* pow currently only supports whole numbers.
*/
pow(exponent: number | bigint): Money {

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

if (exponent > 1) {
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);
}
return base;
}

}

/**
* Returns the absolute value.
*/
Expand Down
25 changes: 25 additions & 0 deletions test/money.ts
Original file line number Diff line number Diff line change
Expand Up @@ -287,6 +287,31 @@ describe('Money class', () => {

});

describe('pow', () => {

const cases: [string|number, number, string][] = [
['1', 5,'1.00'],
['2', 8, '256.00'],
[5, 3, '125.00'],
[-10, 5, '-100000.00'],
[-10, 1, '-10.00'],
[-10, 0, '1.00'],
[2, -2, '0.25'],
];

for (const cas of cases) {

it(`${cas[0]} ** ${cas[1]} = ${cas[2]}`, () => {

const x = new Money(cas[0], 'CAD');
expect(x.pow(cas[1]).toFixed(2)).to.equal(cas[2]);

});

}

});

describe('abs', () => {

const cases = [
Expand Down

0 comments on commit 3211836

Please sign in to comment.