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