*
* @author Georgios Gousios <gousiosg@gmail.com>
*/
-final case class Timeslot(from: Date, to: Date)
- extends DSLItem with Ordered[Timeslot] {
+final case class Timeslot(from: Date, to: Date) extends Ordered[Timeslot] {
/* Preconditions to ensure correct object creations */
assert(from != null)
assert(to != null)
- assert(from.before(to), "from = %s, to = %s".format(new MutableDateCalc(from), new MutableDateCalc(to)))
+ assert(start <= end, "from = %s, to = %s".format(new MutableDateCalc(from), new MutableDateCalc(to)))
def startsBefore(t: Timeslot) : Boolean = start < t.start
*/
def contains(t: Timeslot) : Boolean = this.start <= t.start && this.end >= t.end
+ def weakIncludes(t: Date) : Boolean = start < t.getTime && t.getTime < end
+ def weakOverlaps(t: Timeslot) : Boolean =
+ contains(t) || t.contains(this) || this.weakIncludes(t.from) || this.weakIncludes(t.to)
+
def containsTimeInMillis(millis: Long) = start <= millis && millis <= end
/**
* Check whether this timeslot contains the provided time instant.
*/
- private def includes(t: Date) : Boolean = start <= t.getTime && t.getTime <= end
+ def includes(t: Date) : Boolean = start <= t.getTime && t.getTime <= end
/**
}
}
+ /* align a time slot in "bound_size" boundaries so that
+ * start0 <= start and end0 >= end */
+ def align(bound_size : Long) : Timeslot = {
+ val start0 = (start / bound_size) * bound_size
+ val add_one = if (end % bound_size == 0) 0 else 1
+ val end0 = (end / bound_size + add_one) * bound_size
+ Timeslot(start0,end0)
+ }
+
+ /* returns true when the start and end address are
+ * multiples of bound_size*/
+ def isAligned(bound_size : Long) : Boolean =
+ start % bound_size == 0 && end % bound_size == 0
+
+
/**
* Compares the starting times of two timeslots.
*/
def myString : String = "Timeslot(" + this.start + "," + this.end + ")"
//override def toString() = myString
- override def toString() = toDateString
+ override def toString() =
+ toDateString
def toDateString = "Timeslot(%s, %s)".format(new MutableDateCalc(from), new MutableDateCalc(to))
def toISODateString = "Timeslot(%s, %s)".format(new MutableDateCalc(from).toISOString, new MutableDateCalc(to).toISOString)
def apply(x: Int, y: Int): Timeslot =
new Timeslot(new Date(x), new Date(y))
+
+ def mergeOverlaps(list: List[Timeslot]): List[Timeslot] = {
+ def sorter(x: Timeslot, y: Timeslot) : Boolean = y.from after x.from
+ (list sortWith sorter).foldLeft(List[Timeslot]()) {
+ case (Nil,b) =>
+ List(b)
+ case (hd::Nil,b) =>
+ if (hd overlaps b) (hd merge b)::Nil
+ else b::hd::Nil
+ case (a @ hd::tl,b) =>
+ if(hd overlaps b) (hd merge b)::tl
+ else b :: a
+ }.reverse
+ }
}
\ No newline at end of file