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