Skip to content
Merged
Show file tree
Hide file tree
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
14 changes: 14 additions & 0 deletions spec/std/set_spec.cr
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,20 @@ describe "Set" do
end
end

describe "add?" do
it "returns true when object is not in the set" do
set = Set(Int32).new
set.add?(1).should be_true
end

it "returns false when object is in the set" do
set = Set(Int32).new
set.add?(1).should be_true
set.includes?(1).should be_true
set.add?(1).should be_false
end
end

describe "delete" do
it "deletes an object" do
set = Set{1, 2, 3}
Expand Down
13 changes: 13 additions & 0 deletions src/set.cr
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,19 @@ struct Set(T)
self
end

# Adds *object* to the set and returns `true` on success
# and `false` if the value was already in the set.
#
# ```
# s = Set{1, 5}
# s.add? 8 # => true
# s.add? 8 # => false
# ```
def add?(object : T)
# TODO: optimize the hash lookup call
!!(add(object) unless includes?(object))
end

# Adds `#each` element of *elems* to the set and returns `self`.
#
# ```
Expand Down