File tree 1 file changed +31
-13
lines changed
src/main/scala/scala/collection/decorators
1 file changed +31
-13
lines changed Original file line number Diff line number Diff line change @@ -95,21 +95,39 @@ class IteratorDecorator[A](val `this`: Iterator[A]) extends AnyVal {
95
95
*/
96
96
def splitBy [K ](f : A => K ): Iterator [Iterable [A ]] =
97
97
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
+
101
103
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
110
121
}
111
- seq.toVector
122
+ hd = el
123
+ }
124
+ if (hadSameKey) {
125
+ hdDefined = false
126
+ }
127
+ seq.result()
128
+ }else {
129
+ Iterator .empty.next()
112
130
}
113
- }
131
+ }
114
132
}
115
133
}
You can’t perform that action at this time.
0 commit comments