Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions src/main/kotlin/utils/StringUtils.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
package utils

fun String.cutOff(maxCharsPerLine: Int): String {
require(maxCharsPerLine > 0) { "Character limit should be at least 1" }
return if (length <= maxCharsPerLine) this else "${take(maxCharsPerLine - 1)}…"
}
42 changes: 42 additions & 0 deletions src/test/kotlin/utils/StringUtilsKtTest.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
package utils

import io.kotest.assertions.throwables.shouldThrow
import io.kotest.matchers.equals.shouldBeEqual
import org.junit.jupiter.api.Test

class StringUtilsKtTest {
@Test
fun `when string is less than max character limit, then return same string`() {
val input = "testyy"
input.cutOff(100).shouldBeEqual(input)
}

@Test
fun `when string is longer than max character limit, then return truncated string with ellipsis`() {
val input = "Testyyyyyyyyyyyyyyyyyyyy"
input.cutOff(5).shouldBeEqual("Test…")
}

@Test
fun `when max character limit is negative, then throw exception`() {
val exception =
shouldThrow<IllegalArgumentException> {
"willCrash".cutOff(-10)
}
exception.message?.shouldBeEqual("Character limit should be at least 1")
}

@Test
fun `when max character limit is 0, then throw exception`() {
val exception =
shouldThrow<IllegalArgumentException> {
"willCrash".cutOff(0)
}
exception.message?.shouldBeEqual("Character limit should be at least 1")
}

@Test
fun `when max character limit is 1, then return ellipsis character`() {
"testy".cutOff(1).shouldBeEqual("…")
}
}
Loading