Last active
December 8, 2016 11:46
-
-
Save danneu/e89619e63d036a84c00f311471de81dc to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Example | |
// | |
// val nodes: List<Iterable<Int>> = listOf( | |
// listOf(1), | |
// listOf(2), | |
// listOf(3) | |
// ) | |
// | |
// LazyIteratorChain.fromIterables(nodes).asSequence().toList() == listOf(1, 2, 3) | |
import java.util.Collections | |
abstract class LazyIteratorChain<T>: Iterator<T> { | |
var currIter: Iterator<T> = Collections.emptyIterator() | |
var count = 0 | |
abstract fun nextIterator(count: Int): Iterator<T>? | |
override fun hasNext(): Boolean { | |
while (true) { | |
if (currIter.hasNext()) return true | |
currIter = nextIterator(++count) ?: return false | |
} | |
} | |
override fun next(): T = currIter.next() | |
companion object { | |
fun <T> fromIterables(ables: List<Iterable<T>>) = object : LazyIteratorChain<T>() { | |
override fun nextIterator(count: Int) = ables.getOrNull(count - 1)?.iterator() | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment