File: sorting_spec.rb

package info (click to toggle)
ruby-hamster 3.0.0-4
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, forky, sid, trixie
  • size: 1,932 kB
  • sloc: ruby: 16,915; makefile: 4
file content (60 lines) | stat: -rw-r--r-- 1,618 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
require "spec_helper"
require "hamster/set"

describe Hamster::Set do
  [
    [:sort, ->(left, right) { left.length <=> right.length }],
    [:sort_by, ->(item) { item.length }],
  ].each do |method, comparator|
    describe "##{method}" do
      [
        [[], []],
        [["A"], ["A"]],
        [%w[Ichi Ni San], %w[Ni San Ichi]],
      ].each do |values, expected|
        describe "on #{values.inspect}" do
          let(:set) { S[*values] }

          describe "with a block" do
            let(:result) { set.send(method, &comparator) }

            it "returns #{expected.inspect}" do
              result.should eql(SS.new(expected, &comparator))
              result.to_a.should == expected
            end

            it "doesn't change the original Set" do
              result
              set.should eql(S.new(values))
            end
          end

          describe "without a block" do
            let(:result) { set.send(method) }

            it "returns #{expected.sort.inspect}" do
              result.should eql(SS[*expected])
              result.to_a.should == expected.sort
            end

            it "doesn't change the original Set" do
              result
              set.should eql(S.new(values))
            end
          end
        end
      end
    end
  end

  describe "#sort_by" do
    it "only calls the passed block once for each item" do
      count = 0
      fn    = lambda { |x| count += 1; -x }
      items = 100.times.collect { rand(10000) }.uniq

      S[*items].sort_by(&fn).to_a.should == items.sort.reverse
      count.should == items.length
    end
  end
end