Skip to content

Commit

Permalink
Add 'nice' function from d3 (#283)
Browse files Browse the repository at this point in the history
  • Loading branch information
sdonn3 authored Oct 5, 2023
1 parent 1fa01d1 commit a60aef0
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 0 deletions.
5 changes: 5 additions & 0 deletions scale/api/scale.api
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,11 @@ public final class com/juul/krayon/scale/MinKt {
public static final fun min (Ljava/lang/Iterable;Lkotlin/jvm/functions/Function1;)Ljava/lang/Comparable;
}

public final class com/juul/krayon/scale/NiceKt {
public static final fun nice (DDI)Ljava/util/List;
public static final fun nice (FFI)Ljava/util/List;
}

public abstract interface class com/juul/krayon/scale/Scale {
public abstract fun scale (Ljava/lang/Object;)Ljava/lang/Object;
}
Expand Down
28 changes: 28 additions & 0 deletions scale/src/commonMain/kotlin/Nice.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
package com.juul.krayon.scale

import kotlin.math.ceil
import kotlin.math.floor

/** See equivalent [d3 function](https://github.com/d3/d3-array#nice). */
public fun nice(start: Float, stop: Float, count: Int): List<Float> =
nice(start.toDouble(), stop.toDouble(), count).map { it.toFloat() }

/** See equivalent [d3 function](https://github.com/d3/d3-array#nice). */
public fun nice(start: Double, stop: Double, count: Int): List<Double> {
var nextStart = start
var nextStop = stop
var previousIncrement: Int? = null
while (true) {
val increment = tickIncrement(nextStart, nextStop, count)
if (increment == previousIncrement || increment == 0) {
return listOf(nextStart, nextStop)
} else if (increment > 0) {
nextStart = floor(nextStart / increment) * increment
nextStop = ceil(nextStop / increment) * increment
} else {
nextStart = ceil(nextStart * increment) / increment
nextStop = floor(nextStop * increment) / increment
}
previousIncrement = increment
}
}

0 comments on commit a60aef0

Please sign in to comment.