Skip to content

Commit

Permalink
Add Enumerable(T)#to_set(& : T -> U) : Set(U) forall U (crystal-lan…
Browse files Browse the repository at this point in the history
…g#12654)

Co-authored-by: Johannes Müller <[email protected]>
  • Loading branch information
caspiano and straight-shoota authored Dec 13, 2023
1 parent 6f1067e commit 0b251d4
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 @@ -131,6 +131,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 @@ -495,4 +495,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 0b251d4

Please sign in to comment.