Module: Comparable

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

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.normalize(what) ⇒ Object



2
3
4
5
6
7
8
# File 'opal/opal/corelib/comparable.rb', line 2

def self.normalize(what)
  return what if Integer === what

  return  1 if what > 0
  return -1 if what < 0
  return  0
end

Instance Method Details

#<(other) ⇒ Object



48
49
50
51
52
53
54
# File 'opal/opal/corelib/comparable.rb', line 48

def <(other)
  unless cmp = (self <=> other)
    raise ArgumentError, "comparison of #{self.class} with #{other.class} failed"
  end

  `#{Comparable.normalize(cmp)} < 0`
end

#<=(other) ⇒ Object



56
57
58
59
60
61
62
# File 'opal/opal/corelib/comparable.rb', line 56

def <=(other)
  unless cmp = (self <=> other)
    raise ArgumentError, "comparison of #{self.class} with #{other.class} failed"
  end

  `#{Comparable.normalize(cmp)} <= 0`
end

#==(other) ⇒ Object



10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
# File 'opal/opal/corelib/comparable.rb', line 10

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)

  return `#{Comparable.normalize(cmp)} == 0`
rescue StandardError
  false
end

#>(other) ⇒ Object



32
33
34
35
36
37
38
# File 'opal/opal/corelib/comparable.rb', line 32

def >(other)
  unless cmp = (self <=> other)
    raise ArgumentError, "comparison of #{self.class} with #{other.class} failed"
  end

  `#{Comparable.normalize(cmp)} > 0`
end

#>=(other) ⇒ Object



40
41
42
43
44
45
46
# File 'opal/opal/corelib/comparable.rb', line 40

def >=(other)
  unless cmp = (self <=> other)
    raise ArgumentError, "comparison of #{self.class} with #{other.class} failed"
  end

  `#{Comparable.normalize(cmp)} >= 0`
end

#between?(min, max) ⇒ Boolean

Returns:



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

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

#clamp(min, max) ⇒ Object



70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
# File 'opal/opal/corelib/comparable.rb', line 70

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

  unless cmp
    raise ArgumentError, "comparison of #{min.class} with #{max.class} failed"
  end

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

  return min if Comparable.normalize(self <=> min) < 0
  return max if Comparable.normalize(self <=> max) > 0
  return self
end