Skip to content

Commit

Permalink
resource-iterator: add ResourceIterator#associateTo & `ResourceIter…
Browse files Browse the repository at this point in the history
…ator#associateByTo`
  • Loading branch information
sszuev committed Nov 29, 2023
1 parent 21ba7fd commit 4f9ab6f
Show file tree
Hide file tree
Showing 2 changed files with 57 additions and 0 deletions.
27 changes: 27 additions & 0 deletions src/main/kotlin/Iterators.kt
Original file line number Diff line number Diff line change
Expand Up @@ -151,6 +151,33 @@ fun <T, K, V> ResourceIterator<T>.associate(transform: (T) -> Pair<K, V>): Map<K
asInternalSequence().associate(transform)
}

/**
* Analogy of the `Sequence<T>.associateByTo`.
*/
inline fun <T, K, M : MutableMap<in K, in T>> ResourceIterator<T>.associateByTo(
destination: M,
keySelector: (T) -> K
): M =
use {
for (i in this) {
destination.put(keySelector(i), i)
}
return destination
}

/**
* Analogy of the `Sequence<T>.associateTo`.
*/
inline fun <T, K, V, M : MutableMap<in K, in V>> ResourceIterator<T>.associateTo(
destination: M,
transform: (T) -> Pair<K, V>
): M = use {
for (i in this) {
destination += transform(i)
}
return destination
}

/**
* Returns a new map containing all key-value pairs from the given resource-iterator of pairs.
*
Expand Down
30 changes: 30 additions & 0 deletions src/test/kotlin/ResourceIteratorsTest.kt
Original file line number Diff line number Diff line change
Expand Up @@ -494,4 +494,34 @@ internal class ResourceIteratorTest {
Assertions.assertEquals(9, res)
Assertions.assertEquals(1, onClose)
}

@Test
fun `test associateByTo`() {
var onClose = 0
val res: MutableMap<String, Int> = resourceIteratorOf(42, 42, 4242, 424242) { onClose++ }
.associateByTo(mutableMapOf()) { it.toString() }
Assertions.assertEquals(
mapOf(
"42" to 42, "4242" to 4242, "424242" to 424242
),
res
)
Assertions.assertEquals(1, onClose)
}

@Test
fun `test associateTo`() {
var onClose = 0
val res: MutableMap<Int, Int> = resourceIteratorOf(42, 42, 4242, 424242) { onClose++ }
.associateTo(mutableMapOf()) { a -> a / 2 to a * 2 }
Assertions.assertEquals(
mapOf(
21 to 84,
2121 to 8484,
212121 to 848484,
),
res
)
Assertions.assertEquals(1, onClose)
}
}

0 comments on commit 4f9ab6f

Please sign in to comment.