Skip to content

Commit

Permalink
Implement Hash#{<,<=,>,>=} operators for sub/superset checking
Browse files Browse the repository at this point in the history
  • Loading branch information
Sija committed Mar 3, 2019
1 parent 88a238e commit 9f035f3
Show file tree
Hide file tree
Showing 2 changed files with 63 additions and 0 deletions.
40 changes: 40 additions & 0 deletions spec/std/hash_spec.cr
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,46 @@ describe "Hash" do
end
end

describe "<" do
it do
h1 = {"a" => 1, "b" => 2}
h2 = {"a" => 1, "b" => 2, "c" => 3}
(h1 < h2).should be_true
(h2 < h1).should be_false
(h1 < h1).should be_false
end
end

describe "<=" do
it do
h1 = {"a" => 1, "b" => 2}
h2 = {"a" => 1, "b" => 2, "c" => 3}
(h1 <= h2).should be_true
(h2 <= h1).should be_false
(h1 <= h1).should be_true
end
end

describe ">" do
it do
h1 = {"a" => 1, "b" => 2}
h2 = {"a" => 1, "b" => 2, "c" => 3}
(h1 > h2).should be_false
(h2 > h1).should be_true
(h1 > h1).should be_false
end
end

describe ">=" do
it do
h1 = {"a" => 1, "b" => 2}
h2 = {"a" => 1, "b" => 2, "c" => 3}
(h1 >= h2).should be_false
(h2 >= h1).should be_true
(h1 >= h1).should be_true
end
end

describe "[]" do
it "gets" do
a = {1 => 2}
Expand Down
23 changes: 23 additions & 0 deletions src/hash.cr
Original file line number Diff line number Diff line change
Expand Up @@ -882,6 +882,29 @@ class Hash(K, V)
true
end

# Returns `true` if `self` is subset of *other*.
def <(other : Hash)
return false if self == other
self <= other
end

# Returns `true` if `self` is subset of *other* or equals to *other*.
def <=(other : Hash)
all? do |key, value|
other[key]? == value
end
end

# Returns `true` if *other* is subset of `self`.
def >(other : Hash)
other < self
end

# Returns `true` if *other* is subset of `self` or equals to `self`.
def >=(other : Hash)
other <= self
end

# See `Object#hash(hasher)`
def hash(hasher)
# The hash value must be the same regardless of the
Expand Down

0 comments on commit 9f035f3

Please sign in to comment.