Skip to content

Instantly share code, notes, and snippets.

@Mahoney
Last active August 28, 2024 10:58
Show Gist options
  • Select an option

  • Save Mahoney/b91996ddde973da4f93113475e8d9776 to your computer and use it in GitHub Desktop.

Select an option

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
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