Permalink
Browse files

Graceful handling of uncomparable keys

h["a"] = 1
h[1.1] = 2    # => TypeError because "a" <=> 1.1 returns nil
h.delete(1.1) # => ditto
h[1.1]        # => nil, not error

Closes #4.
  • Loading branch information...
1 parent 3eb7cdc commit da512e6f3449503a2576e791fc6a6f7c6d999168 @nahi committed May 8, 2012
Showing with 36 additions and 2 deletions.
  1. +6 −0 lib/avl_tree.rb
  2. +6 −0 lib/red_black_tree.rb
  3. +12 −1 test/test_avl_tree.rb
  4. +12 −1 test/test_red_black_tree.rb
View
@@ -57,6 +57,8 @@ def insert(key, value)
@value = value
when 1
@right = @right.insert(key, value)
+ else
+ raise TypeError, "cannot compare #{key} and #{@key} with <=>"
end
rotate
end
@@ -70,6 +72,8 @@ def retrieve(key)
@value
when 1
@right.retrieve(key)
+ else
+ nil
end
end
@@ -84,6 +88,8 @@ def delete(key)
when 1
deleted, @right = @right.delete(key)
[deleted, self.rotate]
+ else
+ raise TypeError, "cannot compare #{key} and #{@key} with <=>"
end
end
View
@@ -77,6 +77,8 @@ def insert(key, value)
if black? and @left.black? and @right.red? and !@right.children_both_black?
ret = rebalance_for_right_insert
end
+ else
+ raise TypeError, "cannot compare #{key} and #{@key} with <=>"
end
ret.pullup_red
end
@@ -90,6 +92,8 @@ def retrieve(key)
@value
when 1
@right.retrieve(key)
+ else
+ nil
end
end
@@ -110,6 +114,8 @@ def delete(key)
if rebalance
ret, rebalance = rebalance_for_right_delete
end
+ else
+ raise TypeError, "cannot compare #{key} and #{@key} with <=>"
end
[deleted, ret, rebalance]
end
View
@@ -155,6 +155,15 @@ def test_push
assert_equal 6, h.size
end
+ def test_different_type
+ h = AVLTree.new
+ h['a'] = 1
+ assert_raise(TypeError) do
+ h[3.3] = 2
+ end
+ assert_nil h[3.3]
+ end
+
def test_delete_leaf
h = AVLTree.new
h['b'] = 1
@@ -313,7 +322,9 @@ def test_delete_different_type
h['abc'] = 2
h['bb'] = 3
- assert_nil h.delete(3.3)
+ assert_raise(TypeError) do
+ h.delete(3.3)
+ end
end
def test_each
@@ -169,6 +169,15 @@ def test_push
assert_equal 6, h.size
end
+ def test_different_type
+ h = RedBlackTree.new
+ h['a'] = 1
+ assert_raise(TypeError) do
+ h[3.3] = 2
+ end
+ assert_nil h[3.3]
+ end
+
def test_delete_leaf
h = RedBlackTree.new
h['b'] = 1
@@ -463,7 +472,9 @@ def test_delete_different_type
h['abc'] = 2
h['bb'] = 3
- assert_nil h.delete(3.4)
+ assert_raise(TypeError) do
+ h.delete(3.3)
+ end
end
def test_each

0 comments on commit da512e6

Please sign in to comment.