Last active
October 23, 2020 19:21
-
-
Save jonatbergn/6a8e874a26487c460076d7e049c3d20f to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
typealias Given<Input> = (Input) -> Boolean | |
infix fun <Input, Violation> Given<Input>.violates(violation: Violation): (Input) -> Violation? = | |
{ if (invoke(it)) violation else null } | |
fun <Input> given(checkForFailure: Input.() -> Boolean) = checkForFailure | |
fun <Input, Violation> validatorOf(vararg criteria: (Input) -> Violation?): (Input) -> List<Violation> = | |
{ input -> criteria.mapNotNull { it(input) } } | |
//DEMO | |
enum class PasswordViolation { MustContainUpperCase, MustContainLowerCase, MustContainNumber } | |
fun main(vararg args: String) { | |
val validator = validatorOf( | |
given<String> { equals(toLowerCase()) } violates PasswordViolation.MustContainUpperCase, | |
given<String> { equals(toUpperCase()) } violates PasswordViolation.MustContainLowerCase, | |
given<String> { !contains("[0-9]".toRegex()) } violates PasswordViolation.MustContainNumber | |
) | |
println(validator("input")) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment