2 files+16−10/2 viewed
| 17 | 17 | return ((a % b) + Math.abs(b)) % Math.abs(b); | |
| 18 | 18 | } | |
| 19 | 19 | ||
| 20 | − | module.exports = { add, multiply, mod }; | |
| 20 | + | /** Returns base raised to the whole-number exponent; throws a RangeError if exponent is negative. */ | |
| 21 | + | function power(base, exponent) { | |
| 22 | + | if (exponent < 0) { | |
| 23 | + | throw new RangeError("exponent must not be negative"); | |
| 24 | + | } | |
| 25 | + | let result = 1; | |
| 26 | + | for (let i = 0; i < exponent; i++) { | |
| 27 | + | result *= base; | |
| 28 | + | } | |
| 29 | + | return result; | |
| 30 | + | } | |
| 31 | + | ||
| 32 | + | module.exports = { add, multiply, mod, power }; |
| 8 | 8 | assert.strictEqual(math.mod(6, 3), 0); | |
| 9 | 9 | assert.strictEqual(math.mod(-1, -3), 2); | |
| 10 | 10 | assert.throws(() => math.mod(1, 0), RangeError); | |
| 11 | + | assert.strictEqual(math.power(2, 10), 1024); | |
| 12 | + | assert.strictEqual(math.power(5, 0), 1); | |
| 13 | + | assert.throws(() => math.power(2, -1), RangeError); | |
| 11 | 14 | console.log("all tests passed"); |