From 5ab77513315da8161acbc5b40f8d76d7d9135918 Mon Sep 17 00:00:00 2001 From: Dmitry Kandalov Date: Wed, 11 Oct 2023 14:13:03 +0100 Subject: [PATCH] refactoring allValues() and mapAllValues() --- .../dev/forkhandles/result4k/iterables.kt | 23 +++++++------------ 1 file changed, 8 insertions(+), 15 deletions(-) diff --git a/result4k/core/src/main/kotlin/dev/forkhandles/result4k/iterables.kt b/result4k/core/src/main/kotlin/dev/forkhandles/result4k/iterables.kt index bb59b26..1f4bc11 100644 --- a/result4k/core/src/main/kotlin/dev/forkhandles/result4k/iterables.kt +++ b/result4k/core/src/main/kotlin/dev/forkhandles/result4k/iterables.kt @@ -1,8 +1,10 @@ package dev.forkhandles.result4k - fun Iterable>.allValues(): Result, E> = - Success(map { r -> r.onFailure { return it } }) + mapAllValues { it } + +fun Sequence>.allValues(): Result, E> = + mapAllValues { it } fun Iterable>.anyValues(): List = filterIsInstance>().map { it.value } @@ -19,8 +21,6 @@ fun Iterable>.partition(): Pair, List> { return Pair(oks, errs) } -// Traverse family of functions - fun Iterable.foldResult( initial: Result, operation: (acc: Tʹ, T) -> Result @@ -33,17 +33,10 @@ fun Sequence.foldResult( ): Result = fold(initial) { acc, el -> acc.flatMap { accVal -> operation(accVal, el) } } -fun Iterable.mapAllValues(f: (T) -> Result): Result, E> { - return mutableListOf() - .also { results -> forEach { e -> results.add(f(e).onFailure { return it }) } } +fun Iterable.mapAllValues(f: (T) -> Result): Result, E> = + map { e -> f(e).onFailure { return it } } .let(::Success) -} -fun Sequence.mapAllValues(f: (T) -> Result): Result, E> { - return mutableListOf() - .also { results -> forEach { e -> results.add(f(e).onFailure { return it }) } } +fun Sequence.mapAllValues(f: (T) -> Result): Result, E> = + mapTo(mutableListOf()) { e -> f(e).onFailure { return it } } .let(::Success) -} - -fun Sequence>.allValues(): Result, E> = - mapAllValues { it }