Last active
October 17, 2023 12:19
-
-
Save atomofiron/b8064595375a0295afdf68a8be368a8d 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
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