diff options
author | Yaroslav Klymko <t3hnar@gmail.com> | 2013-06-10 17:57:47 +0300 |
---|---|---|
committer | Yaroslav Klymko <t3hnar@gmail.com> | 2013-06-10 17:57:47 +0300 |
commit | e3d3e1665d150869be4be40b9ce42690e9e9d247 (patch) | |
tree | 01ba57132e72138e91c749fcbcb1f5d219a127b1 /src | |
parent | 41073f8db662906ada4b779f199ea6d5f4bd5e1f (diff) | |
download | scala-e3d3e1665d150869be4be40b9ce42690e9e9d247.tar.gz scala-e3d3e1665d150869be4be40b9ce42690e9e9d247.tar.bz2 scala-e3d3e1665d150869be4be40b9ce42690e9e9d247.zip |
Add Duration.toCoarsest method
Diffstat (limited to 'src')
-rw-r--r-- | src/library/scala/concurrent/duration/Duration.scala | 36 |
1 files changed, 36 insertions, 0 deletions
diff --git a/src/library/scala/concurrent/duration/Duration.scala b/src/library/scala/concurrent/duration/Duration.scala index a24266bf19..9a8844b489 100644 --- a/src/library/scala/concurrent/duration/Duration.scala +++ b/src/library/scala/concurrent/duration/Duration.scala @@ -221,6 +221,8 @@ object Duration { final def toMinutes: Long = fail("toMinutes") final def toHours: Long = fail("toHours") final def toDays: Long = fail("toDays") + + final def toCoarsest: Duration = this } /** @@ -520,6 +522,18 @@ sealed abstract class Duration extends Serializable with Ordered[Duration] { * $ovf */ def plus(other: Duration) = this + other + /** + * Return duration which is equal to this duration but with a coarsest Unit, or self in case it is already the coarsest Unit + * <p/> + * Examples: + * {{{ + * Duration(60, MINUTES).toCoarsest // Duration(1, HOURS) + * Duration(1000, MILLISECONDS).toCoarsest // Duration(1, SECONDS) + * Duration(48, HOURS).toCoarsest // Duration(2, DAYS) + * Duration(5, SECONDS).toCoarsest // Duration(5, SECONDS) + * }}} + */ + def toCoarsest: Duration } object FiniteDuration { @@ -691,6 +705,28 @@ final class FiniteDuration(val length: Long, val unit: TimeUnit) extends Duratio final def isFinite() = true + final def toCoarsest: Duration = { + def loop(length: Long, unit: TimeUnit): FiniteDuration = { + def coarserOrThis(coarser: TimeUnit, divider: Int) = + if (length % divider == 0) loop(length / divider, coarser) + else if (unit == this.unit) this + else FiniteDuration(length, unit) + + unit match { + case DAYS => FiniteDuration(length, unit) + case HOURS => coarserOrThis(DAYS, 24) + case MINUTES => coarserOrThis(HOURS, 60) + case SECONDS => coarserOrThis(MINUTES, 60) + case MILLISECONDS => coarserOrThis(SECONDS, 1000) + case MICROSECONDS => coarserOrThis(MILLISECONDS, 1000) + case NANOSECONDS => coarserOrThis(MICROSECONDS, 1000) + } + } + + if (unit == DAYS || length == 0) this + else loop(length, unit) + } + override def equals(other: Any) = other match { case x: FiniteDuration => toNanos == x.toNanos case _ => super.equals(other) |