Skip to content

Commit

Permalink
Added Enumerable#in_slices_of (#13108)
Browse files Browse the repository at this point in the history
Co-authored-by: Sijawusz Pur Rahnama <sija@sija.pl>
Co-authored-by: Quinton Miller <nicetas.c@gmail.com>
Co-authored-by: Johannes Müller <straightshoota@gmail.com>
  • Loading branch information
4 people committed May 9, 2023
1 parent 98c091e commit c5b81b8
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 0 deletions.
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

0 comments on commit c5b81b8

Please sign in to comment.