Created
June 7, 2020 09:35
-
-
Save tg44/a8257da5831a43465beda4c613647375 to your computer and use it in GitHub Desktop.
Helper to pretty print scala Duration
This file contains hidden or 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
import concurrent.duration._ | |
import scala.annotation.tailrec | |
object PrettyDuration { | |
val timeUnitList: List[TimeUnit] = | |
DAYS :: | |
HOURS :: | |
MINUTES :: | |
SECONDS :: | |
MILLISECONDS :: | |
MICROSECONDS :: | |
NANOSECONDS :: | |
Nil | |
implicit class PrettyPrintableDuration(val duration: Duration) extends AnyVal { | |
@tailrec | |
private def prettyRec(acc: List[FiniteDuration], remUnits: List[TimeUnit], rem: FiniteDuration, isPast: Boolean): String = { | |
remUnits match { | |
case h :: t => | |
if (rem > Duration(1, h)) { | |
val x = Duration(rem.toUnit(h).toLong, h) | |
prettyRec(x :: acc, t, rem - x, isPast) | |
} else { | |
prettyRec(acc, t, rem, isPast) | |
} | |
case Nil => | |
acc.reverse.map(_.toString).mkString(" ") + (if (isPast) " ago" else "") | |
} | |
} | |
def pretty: String = { | |
duration match { | |
case Duration.Zero => "now" | |
case f: FiniteDuration if f < Duration.Zero => prettyRec(Nil, timeUnitList, f * -1, isPast = true) | |
case f: FiniteDuration => prettyRec(Nil, timeUnitList, f, isPast = false) | |
case Duration.Inf => "infinite" | |
case Duration.MinusInf => "minus infinite" | |
case _ => "undefined" | |
} | |
} | |
} | |
} |
MIT
Thanks a lot! I have added localization and limiting the number of parts to this code.
In main branch:
- implementation: https://github.com/arturaz/scala-web-framework/blob/main/shared/src/framework/utils/PrettyPrintDuration.scala
- test: https://github.com/arturaz/scala-web-framework/blob/main/shared/tests/src/framework/utils/PrettyPrintDuration.scala
At the time of posting:
- implementation: https://github.com/arturaz/scala-web-framework/blob/2b2eca91b3b7d971760d88f41b17cbdaa2ec6ac5/shared/src/framework/utils/PrettyPrintDuration.scala
- test: https://github.com/arturaz/scala-web-framework/blob/2b2eca91b3b7d971760d88f41b17cbdaa2ec6ac5/shared/tests/src/framework/utils/PrettyPrintDuration.scala
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hi, thanks for the gist.
What is the licence for this code ?