Last active
August 28, 2024 10:58
-
-
Save Mahoney/b91996ddde973da4f93113475e8d9776 to your computer and use it in GitHub Desktop.
A subtype of Set that presupposes the Set is Ordered and allows random access
This file contains hidden or 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
| interface RandomAccessOrderedSet<out E> : Set<E> { | |
| // Positional Access Operations | |
| /** | |
| * Returns the element at the specified index in the ordered set. | |
| */ | |
| operator fun get(index: Int): E | |
| // Search Operations | |
| /** | |
| * Returns the index of the first occurrence of the specified element in the ordered set, or -1 if the specified | |
| * element is not contained in the set. | |
| */ | |
| fun indexOf(element: @UnsafeVariance E): Int | |
| // List Iterators | |
| /** | |
| * Returns a list iterator over the elements in this ordered set (in proper sequence). | |
| */ | |
| fun listIterator(): ListIterator<E> | |
| /** | |
| * Returns a list iterator over the elements in this ordered set (in proper sequence), starting at the specified [index]. | |
| */ | |
| fun listIterator(index: Int): ListIterator<E> | |
| } | |
| fun <E> randomAccessOrderedSetOf(vararg elements: E): RandomAccessOrderedSet<E> = ListAndSetBackedRandomAccessOrderedSet(setOf(*elements)) | |
| class ListAndSetBackedRandomAccessOrderedSet<out E>( | |
| private val delegate: Set<E> | |
| ) : Set<E> by delegate, RandomAccessOrderedSet<E> { | |
| private val asList by lazy(mode = PUBLICATION) { delegate.toList() } | |
| override operator fun get(index: Int): E = asList[index] | |
| override fun indexOf(element: @UnsafeVariance E): Int = asList.indexOf(element) | |
| override fun listIterator(): ListIterator<E> = asList.listIterator() | |
| override fun listIterator(index: Int): ListIterator<E> = asList.listIterator(index) | |
| fun toList(): List<E> = asList | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment