Skip to content

Commit 8a007ef

Browse files
committed
adds groupUntilChanged extension method on scala.collection.Iterable
1 parent 0e63835 commit 8a007ef

File tree

2 files changed

+41
-0
lines changed

2 files changed

+41
-0
lines changed

src/main/scala/scala/collection/decorators/IterableDecorator.scala

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,4 +33,26 @@ class IterableDecorator[C, I <: IsIterable[C]](coll: C)(implicit val it: I) {
3333
def lazyFoldRight[B](z: B)(op: it.A => Either[B, B => B]): B =
3434
it(coll).iterator.lazyFoldRight(z)(op)
3535

36+
37+
/**
38+
* Constructs an iterator where consecutive elements are accumulated as
39+
* long as the output of f for each element doesn't change.
40+
* <pre>
41+
* Vector(1,2,2,3,3,3,2,2)
42+
* .splitBy(identity)
43+
* </pre>
44+
* produces
45+
* <pre>
46+
* Iterator(Vector(1),
47+
* Vector(2,2),
48+
* Vector(3,3,3),
49+
* Vector(2,2))
50+
* </pre>
51+
* @param f the function to compute a key for an element
52+
* @tparam K the type of the computed key
53+
* @return an iterator of sequences of the consecutive elements with the
54+
* same key in the original iterator
55+
*/
56+
def splitBy[K, That](f: it.A => K)(implicit bf: BuildFrom[C, it.A, That]):Iterator[That] =
57+
it(coll).iterator.splitBy(f).map(bf.fromSpecific(coll))
3658
}

src/test/scala/scala/collection/decorators/IterableDecoratorTest.scala

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -36,4 +36,23 @@ class IterableDecoratorTest {
3636
Assert.assertEquals(2, result2)
3737
}
3838

39+
@Test
40+
def splitByShouldHonorEmptyIterator(): Unit ={
41+
val split = Vector.empty[Int].splitBy(identity)
42+
Assert.assertEquals(split.toVector, Vector.empty)
43+
}
44+
45+
@Test
46+
def splitByShouldReturnSingleSeqWhenAllElHaveTheSameKey(): Unit ={
47+
val value = Vector("1", "1", "1")
48+
val split = value.splitBy(identity).toVector
49+
Assert.assertEquals(split, Vector(value))
50+
}
51+
52+
@Test
53+
def splitByShouldReturnSeqOfConsecutiveElementsWithTheSameKey(): Unit ={
54+
val value = Vector("1", "2","2","3","3","3","2","2")
55+
val split = value.iterator.splitBy(identity).toVector
56+
Assert.assertEquals(split, Vector(Vector("1"), Vector("2","2"), Vector("3","3","3"), Vector("2","2")))
57+
}
3958
}

0 commit comments

Comments
 (0)