Skip to content

Instantly share code, notes, and snippets.

@atomofiron
Last active October 17, 2023 12:19
Show Gist options
  • Save atomofiron/b8064595375a0295afdf68a8be368a8d to your computer and use it in GitHub Desktop.
Save atomofiron/b8064595375a0295afdf68a8be368a8d to your computer and use it in GitHub Desktop.
typealias IteratorProducer<T> = (index: Int) -> T
fun <T> MutableList<T>.addAll(count: Int, producer: IteratorProducer<T>) = addAll(collection(count, producer))
fun <T> iterable(count: Int, producer: IteratorProducer<T>) = object : Iterable<T> {
override fun iterator(): Iterator<T> = iterator(count, producer)
}
fun <T> sequence(count: Int, producer: IteratorProducer<T>) = object : Sequence<T> {
override fun iterator(): Iterator<T> = iterator(count, producer)
}
fun <T> iterator(count: Int, producer: IteratorProducer<T>) = object : Iterator<T> {
private var next = 0
override fun hasNext(): Boolean = next < count
override fun next(): T = when {
hasNext() -> producer(next++)
else -> throw IndexOutOfBoundsException("next index: $next, count: $count")
}
}
fun <T> collection(count: Int, producer: IteratorProducer<T>) = object : Collection<T> {
override val size: Int = count
override fun isEmpty(): Boolean = count == 0
override fun iterator(): Iterator<T> = iterator(count, producer)
override fun containsAll(elements: Collection<T>): Boolean = false
override fun contains(element: T): Boolean = false
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment