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

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

The newest version!
package dev.forkhandles.values

import dev.forkhandles.result4k.Failure
import dev.forkhandles.result4k.Result
import dev.forkhandles.result4k.Success
import dev.forkhandles.result4k.map
import dev.forkhandles.result4k.resultFrom

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

fun , PRIMITIVE : Any> ValueFactory.parseResult4k(value: String) =
    resultFrom { validate(parseFn(value)) }

fun , PRIMITIVE : Any> ValueFactory.ofListResult4k(values: List) =
    values.toResult4k(::ofResult4k)

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

fun , PRIMITIVE : Any> ValueFactory.parseListResult4k(values: List) =
    values.toResult4k(::parseResult4k)

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

fun , PRIMITIVE : Any> ValueFactory.ofResult4k(value: PRIMITIVE) =
    resultFrom { validate(value) }

private fun , PRIMITIVE : Any> List.toResult4k(
    fn: (IN) -> Result
) = when {
    isEmpty() -> Success(emptyList())
    else ->
        drop(1)
            .fold(fn(first()).map(::listOf)) { acc, next ->
                when (acc) {
                    is Success -> fn(next).map { acc.value + it }
                    is Failure -> acc
                }
            }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy