Skip to content

Check if key exists before deleting it #55

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

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
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
3 changes: 2 additions & 1 deletion ext/containers/rbtree_map/rbtree.c
Original file line number Diff line number Diff line change
Expand Up @@ -412,8 +412,9 @@ static VALUE rbtree_max_key(VALUE self) {
static VALUE rbtree_delete(VALUE self, VALUE key) {
VALUE deleted_value;
rbtree *tree = get_tree_from_self(self);
if(!tree->root)
if(get(tree, tree->root, key) == Qnil) {
return Qnil;
}

tree->root = delete(tree, tree->root, key, &deleted_value);
if(tree->root)
Expand Down
2 changes: 1 addition & 1 deletion lib/containers/rb_tree_map.rb
Original file line number Diff line number Diff line change
Expand Up @@ -129,7 +129,7 @@ def max_key
# map.min_key #=> "GA"
def delete(key)
result = nil
if @root
if @root && get(key)
@root, result = delete_recursive(@root, key)
@root.color = :black if @root
end
Expand Down
7 changes: 6 additions & 1 deletion spec/rb_tree_map_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@
shared_examples "non-empty rbtree" do
before(:each) do
@num_items = 1000
@non_existing_element = @num_items+1
@random_array = Array.new(@num_items) { rand(@num_items) }
@random_array.each { |x| @tree[x] = x }
end
Expand All @@ -51,7 +52,7 @@
end

it "should not #has_key? keys it doesn't have" do
expect(@tree.has_key?(100000)).to be false
expect(@tree.has_key?(@non_existing_element)).to be false
end

it "should #has_key? keys it does have" do
Expand Down Expand Up @@ -88,6 +89,10 @@
counter += 1
end
end

it "should allow deleting non-existent keys" do
expect(@tree.delete(@non_existing_element)).to be_nil
end
end

describe "empty rbtreemap" do
Expand Down