Skip to content

Commit 87e7b54

Browse files
authored
Duration Comparison (#262)
1 parent 6ca1bc2 commit 87e7b54

File tree

3 files changed

+21
-7
lines changed

3 files changed

+21
-7
lines changed

arrow-libs/fx/arrow-fx-test/src/main/kotlin/arrow/fx/test/generators/Generators.kt

+4
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ import arrow.fx.DecisionPartialOf
99
import arrow.fx.ForIO
1010
import arrow.fx.IO
1111
import arrow.fx.Schedule
12+
import arrow.fx.typeclasses.Duration
1213
import arrow.fx.typeclasses.Fiber
1314
import arrow.fx.typeclasses.FiberPartialOf
1415
import arrow.fx.typeclasses.nanoseconds
@@ -22,6 +23,9 @@ fun <F, A, E> Gen<E>.raiseError(AP: ApplicativeError<F, E>): Gen<Kind<F, A>> =
2223

2324
fun Gen.Companion.timeUnit(): Gen<TimeUnit> = Gen.from(TimeUnit.values())
2425

26+
fun duration(): Gen<Duration> =
27+
Gen.bind(Gen.long(), Gen.timeUnit(), ::Duration)
28+
2529
fun IO.Companion.genK() = object : GenK<ForIO> {
2630
override fun <A> genK(gen: Gen<A>): Gen<Kind<ForIO, A>> = Gen.oneOf(
2731
gen.map(IO.Companion::just),

arrow-libs/fx/arrow-fx/src/main/kotlin/arrow/fx/typeclasses/Duration.kt

+9
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,15 @@ data class Duration(val amount: Long, val timeUnit: TimeUnit) {
2020
else -> d + this // Swap this and d to add to the smaller unit
2121
}
2222
}
23+
24+
operator fun compareTo(d: Duration): Int = run {
25+
val comp = timeUnit.compareTo(d.timeUnit)
26+
when {
27+
comp == 0 -> amount.compareTo(d.amount)
28+
comp < 0 -> amount.compareTo(timeUnit.convert(d.amount, d.timeUnit))
29+
else -> -d.compareTo(this)
30+
}
31+
}
2332
}
2433

2534
operator fun Int.times(d: Duration) = d * this
Original file line numberDiff line numberDiff line change
@@ -1,21 +1,22 @@
11
package arrow.fx.data
22

33
import arrow.core.test.UnitSpec
4-
import arrow.core.test.generators.intSmall
5-
import arrow.fx.typeclasses.Duration
6-
import arrow.fx.test.generators.timeUnit
7-
import io.kotlintest.properties.Gen
84
import io.kotlintest.properties.forAll
5+
import arrow.fx.test.generators.duration
96

107
class DurationTest : UnitSpec() {
118

129
init {
1310
"plus should be commutative" {
14-
forAll(Gen.intSmall(), Gen.timeUnit(), Gen.intSmall(), Gen.timeUnit()) { i, u, j, v ->
15-
val a = Duration(i.toLong(), u)
16-
val b = Duration(j.toLong(), v)
11+
forAll(duration(), duration()) { a, b ->
1712
a + b == b + a
1813
}
1914
}
15+
16+
"comparison should correct in both directions" {
17+
forAll(duration(), duration()) { a, b ->
18+
a < b == b > a
19+
}
20+
}
2021
}
2122
}

0 commit comments

Comments
 (0)