Skip to content

Instantly share code, notes, and snippets.

@jonatbergn
Last active October 23, 2020 19:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jonatbergn/6a8e874a26487c460076d7e049c3d20f to your computer and use it in GitHub Desktop.
Save jonatbergn/6a8e874a26487c460076d7e049c3d20f to your computer and use it in GitHub Desktop.
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