Skip to content

Commit

Permalink
Add Enumerable#partition overload with type filter (#13572)
Browse files Browse the repository at this point in the history
  • Loading branch information
baseballlover723 authored Jun 21, 2023
1 parent 9bbfb51 commit 739461f
Show file tree
Hide file tree
Showing 2 changed files with 55 additions and 0 deletions.
32 changes: 32 additions & 0 deletions spec/std/enumerable_spec.cr
Original file line number Diff line number Diff line change
Expand Up @@ -1049,6 +1049,38 @@ describe "Enumerable" do
describe "partition" do
it { [1, 2, 2, 3].partition { |x| x == 2 }.should eq({[2, 2], [1, 3]}) }
it { [1, 2, 3, 4, 5, 6].partition(&.even?).should eq({[2, 4, 6], [1, 3, 5]}) }

it "with mono type on union type" do
ints, others = [1, true, nil, 3, false, "string", 'c'].partition(Int32)
ints.should eq([1, 3])
others.should eq([true, nil, false, "string", 'c'])
ints.should be_a(Array(Int32))
others.should be_a(Array(Bool | String | Char | Nil))
end

it "with union type on union type" do
ints_bools, others = [1, true, nil, 3, false, "string", 'c'].partition(Int32 | Bool)
ints_bools.should eq([1, true, 3, false])
others.should eq([nil, "string", 'c'])
ints_bools.should be_a(Array(Int32 | Bool))
others.should be_a(Array(String | Char | Nil))
end

it "with missing type on union type" do
symbols, others = [1, true, nil, 3, false, "string", 'c'].partition(Symbol)
symbols.empty?.should be_true
others.should eq([1, true, nil, 3, false, "string", 'c'])
symbols.should be_a(Array(Symbol))
others.should be_a(Array(Int32 | Bool | String | Char | Nil))
end

it "with mono type on mono type" do
ints, others = [1, 3].partition(Int32)
ints.should eq([1, 3])
others.empty?.should be_true
ints.should be_a(Array(Int32))
others.should be_a(Array(NoReturn))
end
end

describe "reject" do
Expand Down
23 changes: 23 additions & 0 deletions src/enumerable.cr
Original file line number Diff line number Diff line change
Expand Up @@ -1441,6 +1441,29 @@ module Enumerable(T)
{a, b}
end

# Returns a `Tuple` with two arrays. The first one contains the elements
# in the collection that are of the given *type*,
# and the second one that are **not** of the given *type*.
#
# ```
# ints, others = [1, true, nil, 3, false, "string", 'c'].partition(Int32)
# ints # => [1, 3]
# others # => [true, nil, false, "string", 'c']
# typeof(ints) # => Array(Int32)
# typeof(others) # => Array(String | Char | Nil)
# ```
def partition(type : U.class) forall U
a = [] of U
b = [] of typeof(begin
e = Enumerable.element_type(self)
e.is_a?(U) ? raise("") : e
end)
each do |e|
e.is_a?(U) ? a.push(e) : b.push(e)
end
{a, b}
end

# Returns an `Array` with all the elements in the collection for which
# the passed block is falsey.
#
Expand Down

0 comments on commit 739461f

Please sign in to comment.