All Downloads are FREE. Search and download functionalities are using the official Maven repository.

dev.forkhandles.values.result.kt Maven / Gradle / Ivy

The newest version!
package dev.forkhandles.values

/**
 * Return a Result Success/Failure based on validation.
 */

fun , PRIMITIVE : Any> ValueFactory.parseResult(value: String) =
    Result.runCatching { validate(parseFn(value)) }

fun , PRIMITIVE : Any> ValueFactory.ofListResult(values: List) =
    values.toResult(::ofResult)

fun , PRIMITIVE : Any> ValueFactory.ofListResult(vararg values: PRIMITIVE) =
    ofListResult(values.toList())

fun , PRIMITIVE : Any> ValueFactory.parseListResult(values: List) =
    values.toResult(::parseResult)

fun , PRIMITIVE : Any> ValueFactory.parseListResult(vararg values: String) =
    parseListResult(values.toList())

fun , PRIMITIVE : Any> ValueFactory.ofResult(value: PRIMITIVE) =
    Result.runCatching { validate(value) }

private fun , PRIMITIVE : Any> List.toResult(
    fn: (IN) -> Result
) = when {
    isEmpty() -> Result.success(emptyList())
    else ->
        drop(1)
            .fold(fn(first()).map(::listOf)) { acc, next ->
                when {
                    acc.isSuccess -> fn(next).map { acc.getOrThrow() + it }
                    else -> acc
                }
            }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy