Skip to content

Commit

Permalink
Merge pull request #223 from robstoll/feature/mapFirst-second
Browse files Browse the repository at this point in the history
Pair.mapFirst/mapSecond
  • Loading branch information
robstoll authored May 31, 2024
2 parents a02fbc8 + 90b76e3 commit efb096a
Show file tree
Hide file tree
Showing 3 changed files with 60 additions and 0 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ in the stdlib such as:
- blankToNull
- isNotNullAndNotEmpty
- identity
- Pair.mapFirst/Second

and more, see the [Documentation](https://robstoll.github.io/kbox/kdoc/) for a full list.

Expand Down
21 changes: 21 additions & 0 deletions src/commonMain/kotlin/ch/tutteli/kbox/mapPair.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
package ch.tutteli.kbox

/**
* Maps the first element of this [Pair] with the given function [transform].
*
* @return A new pair with the result of the transformation as first and the existing second as second element.
*
* @since 1.3.0
*/
fun <FirstT, SecondT, R> Pair<FirstT, SecondT>.mapFirst(transform: (FirstT) -> R): Pair<R, SecondT> =
Pair(transform(first), second)

/**
* Maps the second element of this [Pair] with the given function [transform].
*
* @return A new pair with the existing first element as first and the result of the transformation as second element.
*
* @since 1.3.0
*/
fun <FirstT, SecondT, R> Pair<FirstT, SecondT>.mapSecond(transform: (SecondT) -> R): Pair<FirstT, R> =
Pair(first, transform(second))
38 changes: 38 additions & 0 deletions src/commonTest/kotlin/ch/tutteli/kbox/MapPairTest.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
package ch.tutteli.kbox

import ch.tutteli.atrium.api.fluent.en_GB.first
import ch.tutteli.atrium.api.fluent.en_GB.second
import ch.tutteli.atrium.api.fluent.en_GB.toBeTheInstance
import ch.tutteli.atrium.api.fluent.en_GB.toEqual
import ch.tutteli.atrium.api.verbs.expect
import kotlin.test.Test

class MapTupleTest {
@Test
fun mapFirst_identity_returns_equal_pair() {
expect(Pair(1, "hello").mapFirst(::identity)).toEqual(Pair(1, "hello"))
}

@Test
fun mapFirst_returns_transformation_does_not_touch_second_element() {
val obj = listOf('h', 'e', 'l', 'l', 'o')
expect(Pair(1, obj).mapFirst { it + 1 }) {
toEqual(Pair(2, obj))
second.toBeTheInstance(obj)
}
}

@Test
fun mapSecond_identity_returns_equal_pair() {
expect(Pair(1, "hello").mapSecond(::identity)).toEqual(Pair(1, "hello"))
}

@Test
fun mapSecond_returns_transformation_does_not_touch_first_element() {
val obj = listOf('h', 'e', 'l', 'l', 'o')
expect(Pair(obj, 1).mapSecond { it + 1 }) {
toEqual(Pair(obj, 2))
first.toBeTheInstance(obj)
}
}
}

0 comments on commit efb096a

Please sign in to comment.