Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

extend OrderedSet with convenience methods ensure_at_front/end.. #981

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
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
}
}