Skip to content

Commit

Permalink
Add Enumerable(T)#to_set(& : T -> U) : Set(U) forall U
Browse files Browse the repository at this point in the history
  • Loading branch information
caspiano committed Oct 24, 2022
1 parent 0b10d13 commit 6567e3b
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 0 deletions.
14 changes: 14 additions & 0 deletions spec/std/enumerable_spec.cr
Original file line number Diff line number Diff line change
Expand Up @@ -130,6 +130,20 @@ describe "Enumerable" do
end
end

describe "#to_set" do
context "without block" do
it "creates a Set from the unique elements of the collection" do
{1, 1, 2, 3}.to_set.should eq Set{1, 2, 3}
end
end

context "with block" do
it "creates a Set from running the block against the collection's elements" do
{1, 2, 3, 4, 5}.to_set { |i| i // 2 }.should eq Set{0, 1, 2}
end
end
end

describe "chunk" do
it "works" do
[1].chunk { true }.to_a.should eq [{true, [1]}]
Expand Down
10 changes: 10 additions & 0 deletions src/set.cr
Original file line number Diff line number Diff line change
Expand Up @@ -486,4 +486,14 @@ module Enumerable
def to_set : Set(T)
Set.new(self)
end

# Returns a new `Set` with the unique results of running *block* against each
# element of the enumerable.
def to_set(&block : T -> U) : Set(U) forall U
set = Set(U).new
each do |elem|
set << yield elem
end
set
end
end

0 comments on commit 6567e3b

Please sign in to comment.