File: comparable_spec.cr

package info (click to toggle)
crystal 1.14.0%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 24,384 kB
  • sloc: javascript: 6,400; sh: 695; makefile: 269; ansic: 121; python: 105; cpp: 77; xml: 32
file content (94 lines) | stat: -rw-r--r-- 2,295 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
require "spec"

private class ComparableTestClass
  include Comparable(Int)

  def initialize(@value : Int32, @return_nil = false)
  end

  def <=>(other : Int)
    return nil if @return_nil

    @value <=> other
  end
end

describe Comparable do
  it "can compare against Int (#2461)" do
    obj = ComparableTestClass.new(4)
    (obj == 3).should be_false
    (obj == 4).should be_true

    (obj < 3).should be_false
    (obj < 4).should be_false

    (obj > 3).should be_true
    (obj > 4).should be_false

    (obj <= 3).should be_false
    (obj <= 4).should be_true
    (obj <= 5).should be_true

    (obj >= 3).should be_true
    (obj >= 4).should be_true
    (obj >= 5).should be_false
  end

  it "checks for nil" do
    obj = ComparableTestClass.new(4, return_nil: true)

    (obj < 1).should be_false
    (obj <= 1).should be_false
    (obj == 1).should be_false
    (obj >= 1).should be_false
    (obj > 1).should be_false
  end

  describe "clamp" do
    describe "number" do
      it "clamps integers" do
        -5.clamp(-10, 100).should eq(-5)
        -5.clamp(10, 100).should eq(10)
        5.clamp(10, 100).should eq(10)
        50.clamp(10, 100).should eq(50)
        500.clamp(10, 100).should eq(100)

        50.clamp(10..100).should eq(50)

        50.clamp(10..nil).should eq(50)
        50.clamp(10...nil).should eq(50)
        5.clamp(10..nil).should eq(10)
        5.clamp(10...nil).should eq(10)

        5.clamp(nil..10).should eq(5)
        50.clamp(nil..10).should eq(10)
      end

      it "clamps floats" do
        -5.5.clamp(-10.1, 100.1).should eq(-5.5)
        -5.5.clamp(10.1, 100.1).should eq(10.1)
        5.5.clamp(10.1, 100.1).should eq(10.1)
        50.5.clamp(10.1, 100.1).should eq(50.5)
        500.5.clamp(10.1, 100.1).should eq(100.1)

        50.5.clamp(10.1..100.1).should eq(50.5)
      end

      it "fails with an exclusive range" do
        expect_raises(ArgumentError) do
          range = Range.new(1, 2, exclusive: true)
          5.clamp(range)
        end
      end
    end

    describe "String" do
      it "clamps strings" do
        "e".clamp("a", "s").should eq "e"
        "e".clamp("f", "s").should eq "f"
        "e".clamp("a", "c").should eq "c"
        "this".clamp("thief", "thin").should eq "thin"
      end
    end
  end
end