Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add Enumerable#in_slices_of #13108

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions spec/std/enumerable_spec.cr
Original file line number Diff line number Diff line change
Expand Up @@ -569,6 +569,19 @@ describe "Enumerable" do
end
end

describe "in slices of" do
it { [1, 2, 3].in_slices_of(1).should eq([[1], [2], [3]]) }
it { [1, 2, 3].in_slices_of(2).should eq([[1, 2], [3]]) }
it { [1, 2, 3, 4].in_slices_of(3).should eq([[1, 2, 3], [4]]) }
it { ([] of Int32).in_slices_of(2).should eq([] of Array(Int32)) }

it "raises argument error if size is less than 0" do
expect_raises ArgumentError, "Size must be positive" do
[1, 2, 3].in_slices_of(0)
end
end
end

describe "includes?" do
it "is true if the object exists in the collection" do
[1, 2, 3].includes?(2).should be_true
Expand Down
16 changes: 16 additions & 0 deletions src/enumerable.cr
Original file line number Diff line number Diff line change
Expand Up @@ -629,6 +629,22 @@ module Enumerable(T)
end
end

# Returns an `Array` with chunks in the given size.
# Last chunk can be smaller depending on the number of remaining items.
#
# ```
# [1, 2, 3].in_slices_of(2) # => [[1, 2], [3]]
# ```
def in_slices_of(size : Int) : Array(Array(T))
raise ArgumentError.new("Size must be positive") if size <= 0

ary = Array(Array(T)).new
each_slice_internal(size, Array(T), false) do |slice|
ary << slice
end
ary
end

# Returns `true` if the collection contains *obj*, `false` otherwise.
#
# ```
Expand Down