Skip to content

Commit 718abf1

Browse files
committed
adds memoization for f(hd)
1 parent b3180ab commit 718abf1

File tree

1 file changed

+9
-4
lines changed

1 file changed

+9
-4
lines changed

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

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -97,6 +97,7 @@ class IteratorDecorator[A](val `this`: Iterator[A]) extends AnyVal {
9797
def splitBy[K](f: A => K): Iterator[immutable.Seq[A]] =
9898
new AbstractIterator[immutable.Seq[A]] {
9999
private var hd: A = _
100+
private var hdKey: K = _
100101
private var hdDefined: Boolean = false
101102

102103
override def hasNext: Boolean = hdDefined || `this`.hasNext
@@ -107,20 +108,24 @@ class IteratorDecorator[A](val `this`: Iterator[A]) extends AnyVal {
107108
if (hdDefined) {
108109
seq += hd
109110
} else {
110-
hd = `this`.next()
111+
val init = `this`.next()
112+
hd = init
113+
hdKey = f(init)
111114
hdDefined = true
112-
seq += hd
115+
seq += init
113116
}
114117
var hadSameKey = true
115118
while (`this`.hasNext && hadSameKey) {
116119
val el = `this`.next()
117120
hdDefined = true
118-
if (f(el) == f(hd)) {
121+
val key = f(el)
122+
if (key == hdKey) {
119123
seq += el
120124
} else {
121125
hadSameKey = false
126+
hdKey = key
127+
hd = el
122128
}
123-
hd = el
124129
}
125130
if (hadSameKey) {
126131
hdDefined = false

0 commit comments

Comments
 (0)