Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add 'nice' function from d3 #283

Merged
merged 2 commits into from
Oct 5, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
}
twyatt marked this conversation as resolved.
Show resolved Hide resolved
}
Loading