diff --git a/java/java-impl/src/com/intellij/util/collections.kt b/java/java-impl/src/com/intellij/util/collections.kt new file mode 100644 index 000000000000..800a3936ba34 --- /dev/null +++ b/java/java-impl/src/com/intellij/util/collections.kt @@ -0,0 +1,43 @@ +/* + * Copyright 2000-2017 JetBrains s.r.o. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.intellij.util + +typealias LookbackValue = Pair + +/** + * @return sequence of `Pair(value, previousValue)`. First element of sequence has `null` previous value. + */ +fun Sequence.withPrevious(): Sequence> = LookbackSequence(this) + + +private class LookbackSequence(private val sequence: Sequence) : Sequence> { + + override fun iterator(): Iterator> = LookbackIterator(sequence.iterator()) +} + +private class LookbackIterator(private val iterator: Iterator) : Iterator> { + + private var previous: T? = null + + override fun hasNext() = iterator.hasNext() + + override fun next(): LookbackValue { + val next = iterator.next() + val result = LookbackValue(next, previous) + previous = next + return result + } +}