Skip to content

Commit 3e979ac

Browse files
committed
Sorted range methods
1 parent 7c76007 commit 3e979ac

File tree

2 files changed

+59
-0
lines changed

2 files changed

+59
-0
lines changed

src/main/scala-2.11_2.12/scala/collection/compat/package.scala

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,12 @@ package object compat {
4848
def lazyAppendAll(as: => TraversableOnce[A]): Stream[A] = stream.append(as)
4949
}
5050

51+
implicit class SortedExtensionMethods[K, T <: Sorted[K, T]](private val fact: Sorted[K, T]) {
52+
def rangeFrom(from: K): T = fact.from(from)
53+
def rangeTo(to: K): T = fact.to(to)
54+
def rangeUntil(until: K): T = fact.until(until)
55+
}
56+
5157
// This really belongs into scala.collection but there's already a package object in scala-library so we can't add to it
5258
type IterableOnce[+X] = TraversableOnce[X]
5359
}
Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
package scala.collection.generic
2+
3+
import org.junit.Test
4+
import org.junit.Assert._
5+
6+
import scala.collection.compat._
7+
import scala.collection.{immutable => i, mutable => m}
8+
9+
class SortedTest {
10+
@Test
11+
def immutableRangeOps(): Unit = {
12+
val st = i.SortedSet(-1, 2, 4, 3)
13+
for (x <- List(0, 1, 4, -1, -4)) {
14+
val s1 = st.rangeFrom(x)
15+
assertEquals(s1: i.SortedSet[Int], st.from(x))
16+
val s2 = st.rangeTo(x)
17+
assertEquals(s2: i.SortedSet[Int], st.to(x))
18+
val s3 = st.rangeUntil(x)
19+
assertEquals(s3: i.SortedSet[Int], st.until(x))
20+
}
21+
val mp = i.SortedMap("" -> 0, "ds" -> -3, "-??" -> 13, "Df" -> 33, "d!" -> -32)
22+
for (x <- List("", "-", "@", "aa", "D", "d")) {
23+
val m1 = mp.rangeFrom(x)
24+
assertEquals(m1: i.SortedMap[String, Int], mp.from(x))
25+
val m2 = mp.rangeTo(x)
26+
assertEquals(m2: i.SortedMap[String, Int], mp.to(x))
27+
val m3 = mp.rangeUntil(x)
28+
assertEquals(m3: i.SortedMap[String, Int], mp.until(x))
29+
}
30+
}
31+
32+
@Test
33+
def mutableRangeOps(): Unit = {
34+
val st = m.SortedSet(-1, 2, 4, 3)
35+
for (x <- List(0, 1, 4, -1, -4)) {
36+
val s1 = st.rangeFrom(x)
37+
assertEquals(s1: m.SortedSet[Int], st.from(x))
38+
val s2 = st.rangeTo(x)
39+
assertEquals(s2: m.SortedSet[Int], st.to(x))
40+
val s3 = st.rangeUntil(x)
41+
assertEquals(s3: m.SortedSet[Int], st.until(x))
42+
}
43+
val mp = m.SortedMap("" -> 0, "ds" -> -3, "-??" -> 13, "Df" -> 33, "d!" -> -32)
44+
for (x <- List("", "-", "@", "aa", "D", "d")) {
45+
val m1 = mp.rangeFrom(x)
46+
assertEquals(m1: m.SortedMap[String, Int], mp.from(x))
47+
val m2 = mp.rangeTo(x)
48+
assertEquals(m2: m.SortedMap[String, Int], mp.to(x))
49+
val m3 = mp.rangeUntil(x)
50+
assertEquals(m3: m.SortedMap[String, Int], mp.until(x))
51+
}
52+
}
53+
}

0 commit comments

Comments
 (0)