From ea71808f40d9add7a31ab152055b8b98570ca5fd Mon Sep 17 00:00:00 2001 From: sorellla Date: Wed, 17 Sep 2025 19:58:36 +0200 Subject: [PATCH] #128: add cutOff function --- src/main/kotlin/utils/StringUtils.kt | 6 ++++ src/test/kotlin/utils/StringUtilsKtTest.kt | 42 ++++++++++++++++++++++ 2 files changed, 48 insertions(+) create mode 100644 src/main/kotlin/utils/StringUtils.kt create mode 100644 src/test/kotlin/utils/StringUtilsKtTest.kt 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("…") + } +}