Skip to content

Commit b9aac24

Browse files
committed
add helpers to run sum calculations in an async fashion
1 parent e1a2a51 commit b9aac24

File tree

3 files changed

+73
-0
lines changed

3 files changed

+73
-0
lines changed

build.gradle.kts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ group = Publishing.GroupId
77
version = Publishing.Version
88

99
dependencies {
10+
implementation(libs.kotlin.coroutines)
1011
implementation(libs.kotlin.stdlib)
1112
implementation(libs.soberg.aoc.api)
1213

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
package com.soberg.aoc.utlities.extensions
2+
3+
import kotlinx.coroutines.CoroutineDispatcher
4+
import kotlinx.coroutines.Dispatchers
5+
import kotlinx.coroutines.launch
6+
import kotlinx.coroutines.runBlocking
7+
import java.util.concurrent.atomic.AtomicInteger
8+
import java.util.concurrent.atomic.AtomicLong
9+
import kotlin.experimental.ExperimentalTypeInference
10+
11+
@OptIn(ExperimentalTypeInference::class)
12+
@OverloadResolutionByLambdaReturnType
13+
@JvmName("asyncSumOfInt")
14+
inline fun <T> Iterable<T>.asyncSumOf(
15+
dispatcher: CoroutineDispatcher = Dispatchers.Default,
16+
crossinline selector: (T) -> Int,
17+
): Int {
18+
val sum = AtomicInteger()
19+
runBlocking(dispatcher) {
20+
forEach {
21+
launch {
22+
sum.getAndAdd(selector(it))
23+
}
24+
}
25+
}
26+
return sum.get()
27+
}
28+
29+
@OptIn(ExperimentalTypeInference::class)
30+
@OverloadResolutionByLambdaReturnType
31+
@JvmName("asyncSumOfLong")
32+
inline fun <T> Iterable<T>.asyncSumOf(
33+
dispatcher: CoroutineDispatcher = Dispatchers.Default,
34+
crossinline selector: (T) -> Long,
35+
): Long {
36+
val sum = AtomicLong()
37+
runBlocking(dispatcher) {
38+
forEach {
39+
launch {
40+
sum.getAndAdd(selector(it))
41+
}
42+
}
43+
}
44+
return sum.get()
45+
}
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
package com.soberg.aoc.utlities.extensions
2+
3+
import assertk.assertThat
4+
import assertk.assertions.isEqualTo
5+
import org.junit.jupiter.api.Test
6+
7+
class AsyncSumTest {
8+
private val testData = "The quick brown fox jumped over the lazy dog".split(" ")
9+
10+
@Test
11+
fun `return sum of integers`() {
12+
val letterCount = testData.asyncSumOf {
13+
it.length
14+
}
15+
16+
assertThat(letterCount).isEqualTo(36)
17+
}
18+
19+
@Test
20+
fun `return sum of longs`() {
21+
val letterCount = testData.asyncSumOf {
22+
it.length.toLong()
23+
}
24+
25+
assertThat(letterCount).isEqualTo(36)
26+
}
27+
}

0 commit comments

Comments
 (0)