Skip to content

Commit d659dd1

Browse files
committed
fixup! adds groupUntilChanged extension method on scala.collection.Iterator
1 parent d1c3330 commit d659dd1

File tree

1 file changed

+31
-13
lines changed

1 file changed

+31
-13
lines changed

src/main/scala/scala/collection/decorators/IteratorDecorator.scala

Lines changed: 31 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -95,21 +95,39 @@ class IteratorDecorator[A](val `this`: Iterator[A]) extends AnyVal {
9595
*/
9696
def splitBy[K](f: A => K): Iterator[Iterable[A]] =
9797
new AbstractIterator[Seq[A]] {
98-
private var hd: Option[A] = `this`.nextOption()
99-
override def hasNext: Boolean = hd.isDefined
100-
98+
private var hd: A = _
99+
private var hdDefined: Boolean = false
100+
101+
override def hasNext: Boolean = hdDefined || `this`.hasNext
102+
101103
override def next(): Seq[A] = {
102-
hd match {
103-
case None => Iterator.empty.next()
104-
case Some(head) =>
105-
hd = `this`.nextOption()
106-
var seq = mutable.Buffer(head)
107-
while (hd.exists(el => f(el) == f(head))) {
108-
seq = seq ++ hd
109-
hd = `this`.nextOption()
104+
if(hasNext) {
105+
val seq = Vector.newBuilder[A]
106+
if(hdDefined) {
107+
seq += hd
108+
} else {
109+
hd = `this`.next()
110+
hdDefined = true
111+
seq += hd
112+
}
113+
var hadSameKey = true
114+
while(`this`.hasNext && hadSameKey) {
115+
val el = `this`.next()
116+
hdDefined = true
117+
if(f(el) == f(hd)) {
118+
seq += el
119+
}else{
120+
hadSameKey=false
110121
}
111-
seq.toVector
122+
hd = el
123+
}
124+
if(hadSameKey) {
125+
hdDefined = false
126+
}
127+
seq.result()
128+
}else{
129+
Iterator.empty.next()
112130
}
113-
}
131+
}
114132
}
115133
}

0 commit comments

Comments
 (0)