Skip to content
Browse files

List#merge_by

  • Loading branch information...
1 parent 7b537f5 commit 2d4a54b4535d01748c201207cf4a25dc4023d810 @harukizaemon harukizaemon committed
Showing with 82 additions and 4 deletions.
  1. +1 −2 lib/hamster/list.rb
  2. +79 −0 spec/hamster/list/merge_by_spec.rb
  3. +2 −2 spec/hamster/list/merge_spec.rb
View
3 lib/hamster/list.rb
@@ -338,7 +338,7 @@ def indices(object = Undefined, &block)
end
def merge(&comparator)
- return merge { |a, b| a <=> b } unless block_given?
+ return merge_by unless block_given?
Stream.new do
sorted = remove(&:empty?).sort do |a, b|
yield(a.head, b.head)
@@ -357,7 +357,6 @@ def merge_by(&transformer)
next EmptyList if sorted.empty?
Sequence.new(sorted.head.head, sorted.tail.cons(sorted.head.tail).merge_by(&transformer))
end
-
end
def eql?(other)
View
79 spec/hamster/list/merge_by_spec.rb
@@ -0,0 +1,79 @@
+require 'spec_helper'
+
+require 'hamster/list'
+
+describe Hamster::List do
+
+ context "without a comparator" do
+
+ context "on an empty list" do
+
+ subject { Hamster.list }
+
+ it "returns an empty list" do
+ subject.merge_by.should be_empty
+ end
+
+ end
+
+ context "on a single list" do
+
+ let(:list) { Hamster.list(1, 2, 3) }
+
+ subject { Hamster.list(list) }
+
+ it "returns the list" do
+ subject.merge_by.should == list
+ end
+
+ end
+
+ context "with multiple lists" do
+
+ subject { Hamster.list(Hamster.list(3, 6, 7, 8), Hamster.list(1, 2, 4, 5, 9))}
+
+ it "merges the lists based on natural sort order" do
+ subject.merge_by.should == Hamster.list(1, 2, 3, 4, 5, 6, 7, 8, 9)
+ end
+
+ end
+
+ end
+
+ context "with a comparator" do
+
+ context "on an empty list" do
+
+ subject { Hamster.list }
+
+ it "returns an empty list" do
+ subject.merge_by { |item| fail("should never be called") }.should be_empty
+ end
+
+ end
+
+ context "on a single list" do
+
+ let(:list) { Hamster.list(1, 2, 3) }
+
+ subject { Hamster.list(list) }
+
+ it "returns the list" do
+ subject.merge_by { |item| -item }.should == Hamster.list(1, 2, 3)
+ end
+
+ end
+
+ context "with multiple lists" do
+
+ subject { Hamster.list(Hamster.list(8, 7, 6, 3), Hamster.list(9, 5, 4, 2, 1))}
+
+ it "merges the lists based on the specified transformer" do
+ subject.merge_by { |item| -item }.should == Hamster.list(9, 8, 7, 6, 5, 4, 3, 2, 1)
+ end
+
+ end
+
+ end
+
+end
View
4 spec/hamster/list/merge_spec.rb
@@ -47,7 +47,7 @@
subject { Hamster.list }
it "returns an empty list" do
- subject.merge { |a, b| fail }.should be_empty
+ subject.merge { |a, b| fail("should never be called") }.should be_empty
end
end
@@ -59,7 +59,7 @@
subject { Hamster.list(list) }
it "returns the list" do
- subject.merge { |a, b| fail }.should == list
+ subject.merge { |a, b| fail("should never be called") }.should == list
end
end

0 comments on commit 2d4a54b

Please sign in to comment.
Something went wrong with that request. Please try again.