Skip to content

Commit

Permalink
Added lengthOrNull variant
Browse files Browse the repository at this point in the history
  • Loading branch information
sksamuel committed Dec 30, 2023
1 parent 08d9204 commit 4669514
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ fun <I, A, E> Parser<I, A?, E>.notNull(ifNull: () -> E): Parser<I, A, E> =
Parser { input: I -> this@notNull.parse(input).flatMap { it?.right() ?: ifNull().leftNel() } }

/**
* Maps a [Parser] to never fail, by replacing any failing values with null.
* Transforms a [Parser] to never fail, by replacing any failing values with null.
*/
fun <I, A, E> Parser<I, A, E>.failAsNull(): Parser<I, A?, Nothing> =
Parser { input: I -> this@failAsNull.parse(input).fold({ Either.Right(null) }, { it.right() }) }
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import com.sksamuel.tribune.core.flatMap
/**
* Narrows an existing String -> String [Parser] by enforcing an exact length on the input string.
*
* For strings which have length that differs than the given [len] arguments, an invalid is
* For strings which have length that differs than the given [len] arguments, a failure is
* returned with the error message generated by [ifError].
*
* @param len the max length, inclusive
Expand All @@ -25,6 +25,27 @@ fun <I, E> Parser<I, String, E>.length(len: Int, ifError: (String) -> E): Parser
}
}

/**
* Narrows an existing String -> String [Parser] by enforcing an exact length on the input string.
*
* For strings which have length that differs than the given [len] arguments, a failure is
* returned with the error message generated by [ifError].
*
* @param len the max length, inclusive
* @param ifError the error generating function
*
* @return valid if the input string is less than or equal to [len] or an invalid otherwise.
*/
@JvmName("lengthOrNull")
fun <I, E> Parser<I, String?, E>.length(len: Int, ifError: (String) -> E): Parser<I, String?, E> =
flatMap {
when {
it == null -> Either.Right(null)
it.length == len -> it.right()
else -> ifError(it).leftNel()
}
}

/**
* Maps a string producing [Parser] by enforcing a length on the string.
*
Expand Down

0 comments on commit 4669514

Please sign in to comment.