Skip to content

Commit

Permalink
Added variant of trim that operates on nulls
Browse files Browse the repository at this point in the history
  • Loading branch information
sksamuel committed Dec 30, 2023
1 parent 0996104 commit fefb12f
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import com.sksamuel.tribune.core.Parser
import com.sksamuel.tribune.core.filter
import com.sksamuel.tribune.core.flatMap
import com.sksamuel.tribune.core.map
import com.sksamuel.tribune.core.mapIfNotNull

/**
* Modifies the output of a String producing [Parser] by trimming the output string
Expand All @@ -16,6 +17,15 @@ import com.sksamuel.tribune.core.map
*/
fun <I, E> Parser<I, String, E>.trim(): Parser<I, String, E> = map { it.trim() }

/**
* Modifies the output of a nullable String producing [Parser] by trimming the output string
* to remove prefix and suffix whitespace.
*
* @return the output of the underlying parser with whitespace trimmed.
*/
@JvmName("trimOnNullableString")
fun <I, E> Parser<I, String?, E>.trim(): Parser<I, String?, E> = mapIfNotNull { it.trim() }

/**
* Modifies the output of a String producing [Parser] to strip the given [chars].
*/
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,13 @@ class StringTest : FunSpec() {
p.parse("abc ") shouldBe Foo("abc").right()
}

test("trim on nullable") {
val p = Parser<String?>().trim()
p.parse(" abcd ") shouldBe "abcd".right()
p.parse("abc ") shouldBe "abc".right()
p.parse(null) shouldBe null.right()
}

test("uppercase") {
val p = Parser<String>().toUppercase().map { Foo(it) }
p.parse("abcd") shouldBe Foo("ABCD").right()
Expand Down

0 comments on commit fefb12f

Please sign in to comment.