Skip to content

Commit c109f47

Browse files
authored
Merge pull request #55 from reganlaurell/area
Implement Area Calculations
2 parents f561073 + 2b523d0 commit c109f47

File tree

2 files changed

+87
-0
lines changed

2 files changed

+87
-0
lines changed

src/main/kotlin/math/Area.kt

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
package math
2+
3+
import java.lang.IllegalArgumentException
4+
import kotlin.math.pow
5+
6+
/**
7+
* Calculate the area of a rectangle
8+
*
9+
* @param length length of rectangle
10+
* @param width width of rectangle
11+
* @return area of given rectangle
12+
*/
13+
fun areaOfARectangle(length: Double, width: Double) = when {
14+
length > 0 && width > 0 -> length * width
15+
else -> throw IllegalArgumentException("Length and Width must be positive")
16+
}
17+
18+
/**
19+
* Calculate the area of a square
20+
*
21+
* @param sideLength side length of square
22+
* @return area of given square
23+
*/
24+
fun areaOfASquare(sideLength: Double) =
25+
when {
26+
sideLength > 0 -> sideLength * sideLength
27+
else -> throw IllegalArgumentException("Side Length must be positive")
28+
}
29+
30+
/**
31+
* Calculate the area of a triangle
32+
*
33+
* @param base base of triangle
34+
* @param height height of triangle
35+
* @return area of given triangle
36+
*/
37+
fun areaOfATriangle(base: Double, height: Double) =
38+
when {
39+
base > 0 && height > 0 -> base * height / 2
40+
else -> throw IllegalArgumentException("Base and Height must be positive")
41+
}
42+
43+
/**
44+
* Calculate the area of a circle
45+
*
46+
* @param radius radius of circle
47+
* @return area of given circle
48+
*/
49+
fun areaOfACircle(radius: Double) =
50+
when {
51+
radius > 0 -> Math.PI * radius.pow(2.0)
52+
else -> throw IllegalArgumentException("Radius must be positive")
53+
}

src/test/kotlin/math/AreaTest.kt

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
package math
2+
3+
import org.junit.Test
4+
import java.lang.IllegalArgumentException
5+
6+
class AreaTest {
7+
@Test
8+
fun testAreaOfARectangle() = assert(areaOfARectangle(10.0, 5.0) == 50.0)
9+
10+
@Test
11+
fun testAreaOfASquare() = assert(areaOfASquare(5.0) == 25.0)
12+
13+
@Test
14+
fun testAreaOfACircle() = assert(areaOfACircle(1.0) == Math.PI)
15+
16+
@Test
17+
fun testAreaOfATriangle() = assert(areaOfATriangle(5.0, 10.0) == 25.0)
18+
19+
@Test(expected = IllegalArgumentException::class)
20+
fun testAreaWithNegatives() {
21+
areaOfARectangle(-1.0, 0.0)
22+
areaOfASquare(-1.0)
23+
areaOfACircle(-1.0)
24+
areaOfATriangle(-1.0, 1.0)
25+
}
26+
27+
@Test(expected = IllegalArgumentException::class)
28+
fun testAreaWithZeros() {
29+
areaOfARectangle(0.0, 0.0)
30+
areaOfASquare(0.0)
31+
areaOfACircle(0.0)
32+
areaOfATriangle(0.0, 1.0)
33+
}
34+
}

0 commit comments

Comments
 (0)