We all know that you shouldn't assert exact equality for floating-point numbers. assertk comes with a convenient way to do it better:
assertThat(value).isCloseTo(3.0, 0.000001)
I'd like to extend that to arrays:
assertThat(array).isCloseTo(doubleArrayOf(2.0, 3.0), 0.000001)
But the best I can do is:
fun Assert<DoubleArray>.isCloseTo(expected: DoubleArray, delta: Double) {
hasSameSizeAs(expected)
this.matchesPredicate { actual : DoubleArray ->
expected.indices.forEach { index ->
if (!actual[index].isCloseTo(expected[index], epsilon)) {
return@matchesPredicate false
}
}
true
}
}
fun Double.isCloseTo(expected: Double, epsilon: Double): Boolean {
abs(this - expected) <= epsilon
}
Is there any way to reduce this matchesPredicate to something like (pseudocode):
hasElementsMatchingPredicate { index, actual ->
actual.isCloseTo(expected, epsilon)
}