TypeScript recursive power function
This is a power(base, exponent)
function in TypeScript that uses recursion
instead of the Math.pow()
function.
function power(base: number, exponent: number): number {
if (exponent === 0) {
return 1;
}
return base * power(base, exponent - 1);
}
Jest tests:
describe("power", () => {
test("2^x", () => {
expect(power(2, 0)).toBe(1);
expect(power(2, 1)).toBe(2);
expect(power(2, 2)).toBe(4);
expect(power(2, 3)).toBe(8);
expect(power(2, 4)).toBe(16);
})
test("3^x", () => {
expect(power(3, 0)).toBe(1);
expect(power(3, 1)).toBe(3);
expect(power(3, 2)).toBe(9);
expect(power(3, 3)).toBe(27);
expect(power(3, 4)).toBe(81);
})
})