TypeScript recursive power function
This is a productOfArray(numbers)
function in TypeScript that uses recursion.
function productOfArray(numbers: number[]): number {
if (numbers.length === 0) {
return 0;
}
if (numbers.length === 1) {
return numbers[0];
}
return numbers[0] * productOfArray(numbers.slice(1));
}
Jest tests:
describe(productOfArray.name, () => {
test("multiplies array elements together", () => {
expect(productOfArray([])).toBe(0);
expect(productOfArray([5])).toBe(5);
expect(productOfArray([1, 2, 3])).toBe(6);
expect(productOfArray([5, 5, 5])).toBe(125);
expect(productOfArray([8, 8])).toBe(64);
expect(productOfArray([1, 2, 3, 4, 5, 6, 7, 8, 9])).toBe(362880);
});
});