Skip to content

Commit

Permalink
Added asSetFilterNulls
Browse files Browse the repository at this point in the history
  • Loading branch information
sksamuel committed Dec 30, 2023
1 parent b87879b commit b156897
Show file tree
Hide file tree
Showing 3 changed files with 17 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -17,5 +17,20 @@ fun <I, A, E> Parser<I, A, E>.asSet(): Parser<Collection<I>, Set<A>, E> {
}
}

/**
* Lifts an existing [Parser] to support sets of the input types supported by
* the underlying parser. Any nulls produced by the underlying parser will be filtered out
* without erroring.
*
* In other words, given a parser from I to A?, returns a parser from Set<I> to Set<A>.
*
* @return a [Parser] that produces sets
*/
fun <I, A, E> Parser<I, A?, E>.asSetFilterNulls(): Parser<Collection<I>, Set<A>, E> {
return Parser { input ->
input.map { this@asSetFilterNulls.parse(it) }.sequence().map { it.filterNotNull().toSet() }
}
}

fun <I, A, E> Parser.Companion.set(elementParser: Parser<I, A, E>): Parser<Collection<I>, Set<A>, E> =
elementParser.asSet()
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ fun <I, A, E> Parser<I, A?, E>.withDefault(ifNull: () -> A): Parser<I, A, E> =
fun <I, A, E> Parser<I, A, E>.allowNulls(): Parser<I?, A?, E> = nullable()

/**
* Maps an existing non-nullable [Parser] I => A to accept null inputs I? => A?
* Maps an existing [Parser] I => A to accept null inputs I? => A?
*/
fun <I, A, E> Parser<I, A, E>.nullable(): Parser<I?, A?, E> =
Parser { input -> if (input == null) Either.Right(null) else this@nullable.parse(input) }
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ class DoubleTest : FunSpec() {
}

test("parser should support doubles with nullable pass through") {
val p = Parser<String>().double { "not a double" }.allowNulls()
val p = Parser<String>().double { "not a double" }.nullable()
p.parse("123.45").getOrNull() shouldBe 123.45
p.parse(null).getOrNull() shouldBe null
}
Expand Down

0 comments on commit b156897

Please sign in to comment.