Skip to content

Commit

Permalink
IntervalSet test for empty and add toString
Browse files Browse the repository at this point in the history
  • Loading branch information
MasseGuillaume committed Dec 12, 2017
1 parent b022fbd commit 5dbdd6b
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 10 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -10,16 +10,39 @@ class IntervalSet(range: BitSet) {
val otherRange = BitSet((start to end): _*)
(range & otherRange).nonEmpty
}

override def toString: String = {
val intervals =
if(range.isEmpty) Nil
else {
var cur = range.head
var start = cur
val interval = List.newBuilder[(Int, Int)]
range.tail.foreach{bit =>
if(cur + 1 != bit) {
interval += ((start, cur))
start = bit
}
cur = bit
}
interval += ((start, cur))
interval.result()
}

val is = intervals.map{ case (start, end) =>
s"[$start, $end]"
}

s"""IntervalSet(${is.mkString(", ")})"""

}
}

object IntervalSet {
def apply(intervals: (Int, Int)*): IntervalSet =
apply(intervals.toList)

def apply(intervals: List[(Int, Int)]): IntervalSet =
def apply(intervals: Seq[(Int, Int)]): IntervalSet =
new IntervalSet(fromRange(intervals))

private def fromRange(xs: List[(Int, Int)]): BitSet = {
private def fromRange(xs: Seq[(Int, Int)]): BitSet = {
if (xs.isEmpty) {
BitSet()
} else {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,8 @@ import org.scalactic.source.Position
import scalafix.internal.util.IntervalSet

class IntervalSetTest() extends FunSuite {

test("contains") {
val set = IntervalSet((1, 2), (4, 5))
val set = IntervalSet(Seq((1, 2), (4, 5)))
assert(!set.contains(0))
assert(set.contains(1))
assert(set.contains(2))
Expand All @@ -17,13 +16,13 @@ class IntervalSetTest() extends FunSuite {
assert(set.contains(5))
assert(!set.contains(6))

val empty = IntervalSet()
val empty = IntervalSet(Seq())
assert(!empty.contains(0))
assert(!empty.contains(1))
}

test("intersects") {
val set = IntervalSet((1, 2), (5, 8))
val set = IntervalSet(Seq((1, 2), (5, 8)))
def in(start: Int, end: Int)(implicit pos: Position): Unit =
assert(set.intersects(start, end))
def out(start: Int, end: Int)(implicit pos: Position): Unit =
Expand All @@ -50,7 +49,7 @@ class IntervalSetTest() extends FunSuite {
out(0,0) // + |
// format:on

val empty = IntervalSet()
val empty = IntervalSet(Seq())
assert(!empty.intersects(0, 0))
assert(!empty.intersects(0, 1))
}
Expand Down

0 comments on commit 5dbdd6b

Please sign in to comment.