Module: Comparable

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

Overview

helpers: truthy

Instance Method Summary collapse

Instance Method Details

#<(other) ⇒ Object



61
62
63
# File 'opal/opal/corelib/comparable.rb', line 61

def <(other)
  `cmp_or_fail(self, other) < 0`
end

#<=(other) ⇒ Object



65
66
67
# File 'opal/opal/corelib/comparable.rb', line 65

def <=(other)
  `cmp_or_fail(self, other) <= 0`
end

#==(other) ⇒ Object



33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# File 'opal/opal/corelib/comparable.rb', line 33

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

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

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

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

  `normalize(cmp) == 0`
end

#>(other) ⇒ Object



53
54
55
# File 'opal/opal/corelib/comparable.rb', line 53

def >(other)
  `cmp_or_fail(self, other) > 0`
end

#>=(other) ⇒ Object



57
58
59
# File 'opal/opal/corelib/comparable.rb', line 57

def >=(other)
  `cmp_or_fail(self, other) >= 0`
end

#between?(min, max) ⇒ Boolean

Returns:



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

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

#clamp(min, max = nil) ⇒ Object



75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
# File 'opal/opal/corelib/comparable.rb', line 75

def clamp(min, max = nil)
  %x{
    var c, excl;

    if (max === nil) {
      // We are dealing with a new Ruby 2.7 behaviour that we are able to
      // provide a single Range argument instead of 2 Comparables.

      if (!Opal.is_a(min, Opal.Range)) {
        #{::Kernel.raise ::TypeError, "wrong argument type #{min.class} (expected Range)"}
      }

      excl = min.excl;
      max = min.end;
      min = min.begin;

      if (max !== nil && excl) {
        #{::Kernel.raise ::ArgumentError, 'cannot clamp with an exclusive range'}
      }
    }

    if (min !== nil && max !== nil && cmp_or_fail(min, max) > 0) {
      #{::Kernel.raise ::ArgumentError, 'min argument must be smaller than max argument'}
    }

    if (min !== nil) {
      c = cmp_or_fail(self, min);

      if (c == 0) return self;
      if (c < 0) return min;
    }

    if (max !== nil) {
      c = cmp_or_fail(self, max);

      if (c > 0) return max;
    }

    return self;
  }
end