Skip to content

Commit a25856a

Browse files
committed
extend OrderedSet with convenience methods ensure_at_front/end, useful eg in implementing a list of "recent documents"
1 parent e592ed6 commit a25856a

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed

Ordered Set/OrderedSet.swift

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -73,5 +73,38 @@ public class OrderedSet<T: Hashable> {
7373
public func all() -> [T] {
7474
return objects
7575
}
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+
}
76109
}
77110

0 commit comments

Comments
 (0)