File tree Expand file tree Collapse file tree 1 file changed +33
-0
lines changed Expand file tree Collapse file tree 1 file changed +33
-0
lines changed Original file line number Diff line number Diff line change @@ -73,5 +73,38 @@ public class OrderedSet<T: Hashable> {
73
73
public func all( ) -> [ T ] {
74
74
return objects
75
75
}
76
+
77
+ // convenience checker - minimize need for client's knowledge of internals
78
+ public func contains( _ object: T ) -> Bool {
79
+ return indexOfKey [ object] != nil
80
+ }
81
+
82
+ // O(1)
83
+ // append object (removing any existing other occurence)
84
+ public func ensure_at_end( _ object: T ) {
85
+ if contains ( object) {
86
+ remove ( object)
87
+ }
88
+ add ( object)
89
+ }
90
+
91
+ // O(n)
92
+ // prepend object (removing any existing other occurence)
93
+ public func ensure_at_front( _ object: T ) {
94
+ if contains ( object) {
95
+ remove ( object) // could make this more efficient (at the expense of maintenance complexity) by not delegating to remove() and insert()
96
+ // but instead doing manually, and running for loop just once at end
97
+ }
98
+ insert ( object, at: 0 )
99
+
100
+ }
101
+
102
+ func debug_str( ) -> String // useful for printing/debugging
103
+ {
104
+ var str = " OrderedSet: \n "
105
+ str += objects. map { " \( $0) " } . joined ( separator: " , " )
106
+
107
+ return str
108
+ }
76
109
}
77
110
You can’t perform that action at this time.
0 commit comments