Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 32 additions & 1 deletion Ordered Set/OrderedSet.swift
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ public class OrderedSet<T: Hashable> {

// O(n)
public func insert(_ object: T, at index: Int) {
assert(index < objects.count, "Index should be smaller than object count")
assert(index <= objects.count, "Index should be smaller than object count")
assert(index >= 0, "Index should be bigger than 0")

guard indexOfKey[object] == nil else {
Expand Down Expand Up @@ -73,5 +73,36 @@ public class OrderedSet<T: Hashable> {
public func all() -> [T] {
return objects
}

// convenience checker - minimize need for client's knowledge of internals
public func contains(_ object: T) ->Bool {
return indexOfKey[object] != nil
}

// O(1)
// append object (removing any existing other occurrence)
public func ensure_at_end(_ object: T) {
if contains(object) {
remove(object)
}
add(object)
}

// O(n)
// prepend object (removing any existing other occurrence)
public func ensure_at_front(_ object: T) {
if contains(object) {
remove(object) // could make this more efficient (at the expense of maintenance complexity) by not delegating to remove() and insert()
// but instead doing manually, and running for loop just once at end
}
insert(object, at:0)
}

// string representation, useful for printing/debugging
public func debug_str() -> String {
var str = "OrderedSet: \n"
str += objects.map{"\($0)"}.joined(separator: ",")
return str
}
}