Last active
October 22, 2021 21:32
-
-
Save fernandomora/fe20dab23a25290b4be707e6d54a3b52 to your computer and use it in GitHub Desktop.
Helper to pretty print scala Duration
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.intenthq.elasticsearchwriter.duration | |
import java.util.Locale | |
import java.util.concurrent.TimeUnit | |
import scala.concurrent.duration._ | |
object PrettyDuration { | |
private val abbreviate = Map( | |
NANOSECONDS -> "ns", | |
MICROSECONDS -> "μs", | |
MILLISECONDS -> "ms", | |
SECONDS -> "s", | |
MINUTES -> "min", | |
HOURS -> "h", | |
DAYS -> "d" | |
) | |
private val units = TimeUnit.values.reverse | |
implicit class PrettyPrintableDuration(duration: Duration) { | |
def pretty: String = pretty() | |
def pretty(precision: Int = 4): String = duration match { | |
case d: FiniteDuration => | |
val chosenUnit = units.find(_.convert(d.length, d.unit) > 0).getOrElse(NANOSECONDS) | |
val value = d.toUnit(chosenUnit) | |
s"%.${precision}g %s".formatLocal(Locale.ROOT, value, abbreviate(chosenUnit)) | |
case Duration.MinusInf => s"-∞ (minus infinity)" | |
case Duration.Inf => s"∞ (infinity)" | |
case _ => s"undefined" | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment