2 files+16−10/2 viewed
| 17 | 17 | return a / b; | |
| 18 | 18 | } | |
| 19 | 19 | ||
| 20 | − | module.exports = { add, multiply, divide }; | |
| 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, divide, power }; |
| 5 | 5 | assert.strictEqual(math.multiply(4, 5), 20); | |
| 6 | 6 | assert.strictEqual(math.divide(10, 4), 2.5); | |
| 7 | 7 | assert.throws(() => math.divide(1, 0), RangeError); | |
| 8 | + | assert.strictEqual(math.power(2, 10), 1024); | |
| 9 | + | assert.strictEqual(math.power(5, 0), 1); | |
| 10 | + | assert.throws(() => math.power(2, -1), RangeError); | |
| 8 | 11 | console.log("all tests passed"); |