diff --git a/spec/std/set_spec.cr b/spec/std/set_spec.cr index 07c131704c2c..57d55020c483 100644 --- a/spec/std/set_spec.cr +++ b/spec/std/set_spec.cr @@ -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} diff --git a/src/set.cr b/src/set.cr index a8e934368947..c64a824e9e0b 100644 --- a/src/set.cr +++ b/src/set.cr @@ -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`. # # ```