Module: Comparable

Included in:
Numeric, String, Time
Defined in:
opal/opal/corelib/comparable.rb

Instance Method Summary collapse

Instance Method Details

#<(other) ⇒ Object



61
62
63
64
65
66
67
# File 'opal/opal/corelib/comparable.rb', line 61

def <(other)
  unless cmp = (self <=> other)
    `fail_comparison(self, other)`
  end

  `normalize(cmp) < 0`
end

#<=(other) ⇒ Object



69
70
71
72
73
74
75
# File 'opal/opal/corelib/comparable.rb', line 69

def <=(other)
  unless cmp = (self <=> other)
    `fail_comparison(self, other)`
  end

  `normalize(cmp) <= 0`
end

#==(other) ⇒ Object



25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# File 'opal/opal/corelib/comparable.rb', line 25

def ==(other)
  return true if equal?(other)

  %x{
    if (self["$<=>"] == Opal.Kernel["$<=>"]) {
      return false;
    }

    // check for infinite recursion
    if (self.$$comparable) {
      delete self.$$comparable;
      return false;
    }
  }

  return false unless cmp = (self <=> other)

  `normalize(cmp) == 0`
end

#>(other) ⇒ Object



45
46
47
48
49
50
51
# File 'opal/opal/corelib/comparable.rb', line 45

def >(other)
  unless cmp = (self <=> other)
    `fail_comparison(self, other)`
  end

  `normalize(cmp) > 0`
end

#>=(other) ⇒ Object



53
54
55
56
57
58
59
# File 'opal/opal/corelib/comparable.rb', line 53

def >=(other)
  unless cmp = (self <=> other)
    `fail_comparison(self, other)`
  end

  `normalize(cmp) >= 0`
end

#between?(min, max) ⇒ Boolean

Returns:



77
78
79
80
81
# File 'opal/opal/corelib/comparable.rb', line 77

def between?(min, max)
  return false if self < min
  return false if self > max
  true
end

#clamp(min, max) ⇒ Object



83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
# File 'opal/opal/corelib/comparable.rb', line 83

def clamp(min, max)
  cmp = min <=> max

  unless cmp
    `fail_comparison(min, max)`
  end

  if `normalize(cmp) > 0`
    raise ArgumentError, 'min argument must be smaller than max argument'
  end

  return min if `normalize(#{self <=> min}) < 0`
  return max if `normalize(#{self <=> max}) > 0`
  self
end