Skip to content

Commit

Permalink
Comparable: inline _compare_with private method
Browse files Browse the repository at this point in the history
  • Loading branch information
asterite committed Mar 13, 2019
1 parent d34deb5 commit f01a0e9
Showing 1 changed file with 10 additions and 14 deletions.
24 changes: 10 additions & 14 deletions src/comparable.cr
Original file line number Diff line number Diff line change
Expand Up @@ -21,13 +21,15 @@ module Comparable(T)
# Compares this object to *other* based on the receiver’s `<=>` method,
# returning `true` if it returns a value less than zero.
def <(other : T)
_compare_with other, &.<(0)
cmp = self <=> other
cmp ? cmp < 0 : false
end

# Compares this object to *other* based on the receiver’s `<=>` method,
# returning `true` if it returns a value equal or less then zero.
def <=(other : T)
_compare_with other, &.<=(0)
cmp = self <=> other
cmp ? cmp <= 0 : false
end

# Compares this object to *other* based on the receiver’s `<=>` method,
Expand All @@ -43,19 +45,22 @@ module Comparable(T)
return true if other.is_a?(Nil) && self.same?(other)
end

_compare_with other, &.==(0)
cmp = self <=> other
cmp ? cmp == 0 : false
end

# Compares this object to *other* based on the receiver’s `<=>` method,
# returning `true` if it returns a value greater then zero.
def >(other : T)
_compare_with other, &.>(0)
cmp = self <=> other
cmp ? cmp > 0 : false
end

# Compares this object to *other* based on the receiver’s `<=>` method,
# returning `true` if it returns a value equal or greater than zero.
def >=(other : T)
_compare_with other, &.>=(0)
cmp = self <=> other
cmp ? cmp >= 0 : false
end

# The comparison operator. Returns `0` if the two objects are equal,
Expand All @@ -75,13 +80,4 @@ module Comparable(T)
# [3, 1, 2].sort { |x, y| x <=> y } # => [1, 2, 3]
# ```
abstract def <=>(other : T)

private def _compare_with(other : T)
cmp = self <=> other
if cmp
yield cmp
else
false
end
end
end

0 comments on commit f01a0e9

Please sign in to comment.