Created
December 17, 2017 18:56
-
-
Save jakebromberg/6f7708717bd03e75a17095760bb2dbb7 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
struct OrderedSet<Element: Comparable & Hashable> { | |
private let elements: [Element] | |
init<S: Sequence>(_ elements: S) where S.Element == Element { | |
let set = Set<Element>(elements) | |
let array = Array(set) | |
self.elements = array.sorted() | |
} | |
} | |
extension OrderedSet: BidirectionalCollection { | |
func index(before i: Int) -> Int { | |
return elements.index(before: i) | |
} | |
} | |
extension OrderedSet: RandomAccessCollection { | |
public typealias Indices = DefaultRandomAccessIndices<OrderedSet<Element>> | |
public var startIndex: Int { | |
return elements.startIndex | |
} | |
public var endIndex: Int { | |
return elements.endIndex | |
} | |
public subscript(index: Int) -> Element { | |
return elements[index] | |
} | |
public func index(after i: Int) -> Int { | |
return elements.index(after: i) | |
} | |
} | |
func ==<S1: Sequence, S2: Sequence>(lhs: S1, rhs: S2) -> Bool | |
where S1.Element == S2.Element, S1.Element: Equatable { | |
for (x, y) in zip(lhs, rhs) where x != y { | |
return false | |
} | |
return true | |
} | |
assert([1, 2, 3, 4, 5] == OrderedSet([5, 4, 3, 2, 1, 5, 4, 3, 2, 1, 5, 4, 3, 2, 1])) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment