Skip to content

Commit 1fec1c0

Browse files
author
QuantCode Agent
committed
fix: handle division by zero in calculator divide function
Throw an Error('Division by zero') when the divisor is zero instead of returning Infinity/NaN. Add three tests covering normal division, decimal results, and the zero-divisor error case.
1 parent 18a7ef6 commit 1fec1c0

2 files changed

Lines changed: 16 additions & 4 deletions

File tree

src/calculator.ts

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,9 @@ export function multiply(a: number, b: number): number {
1515
return a * b
1616
}
1717

18-
// BUG: Division by zero is not handled
1918
export function divide(a: number, b: number): number {
19+
if (b === 0) {
20+
throw new Error("Division by zero")
21+
}
2022
return a / b
2123
}

test/calculator.test.ts

Lines changed: 13 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,5 @@
11
import { describe, test, expect } from "bun:test"
2-
import { add, subtract, multiply } from "../src/calculator"
3-
4-
// Note: divide is intentionally not tested — has a known bug
2+
import { add, subtract, multiply, divide } from "../src/calculator"
53

64
describe("calculator", () => {
75
test("adds two numbers", () => {
@@ -15,4 +13,16 @@ describe("calculator", () => {
1513
test("multiplies two numbers", () => {
1614
expect(multiply(4, 3)).toBe(12)
1715
})
16+
17+
test("divides two numbers", () => {
18+
expect(divide(10, 2)).toBe(5)
19+
})
20+
21+
test("divides resulting in a decimal", () => {
22+
expect(divide(7, 2)).toBe(3.5)
23+
})
24+
25+
test("throws on division by zero", () => {
26+
expect(() => divide(10, 0)).toThrow("Division by zero")
27+
})
1828
})

0 commit comments

Comments
 (0)