diff --git a/src/main/kotlin/utils/StringUtils.kt b/src/main/kotlin/utils/StringUtils.kt new file mode 100644 index 0000000..0518fa0 --- /dev/null +++ b/src/main/kotlin/utils/StringUtils.kt @@ -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)}…" +} diff --git a/src/test/kotlin/utils/StringUtilsKtTest.kt b/src/test/kotlin/utils/StringUtilsKtTest.kt new file mode 100644 index 0000000..81f9eca --- /dev/null +++ b/src/test/kotlin/utils/StringUtilsKtTest.kt @@ -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 { + "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 { + "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("…") + } +}