Skip to content

Commit

Permalink
Optimized Array#skip (#6946)
Browse files Browse the repository at this point in the history
  • Loading branch information
asterite authored and RX14 committed Oct 16, 2018
1 parent 0c6c721 commit ed033df
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 0 deletions.
13 changes: 13 additions & 0 deletions spec/std/array_spec.cr
Original file line number Diff line number Diff line change
Expand Up @@ -1866,4 +1866,17 @@ describe "Array" do
a = [s, t, u, 12, 13]
a.flatten.to_a.should eq([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13])
end

it "#skip" do
ary = [1, 2, 3]
ary.skip(0).should eq([1, 2, 3])
ary.skip(1).should eq([2, 3])
ary.skip(2).should eq([3])
ary.skip(3).should eq([] of Int32)
ary.skip(4).should eq([] of Int32)

expect_raises(ArgumentError, "Attempt to skip negative size") do
ary.skip(-1)
end
end
end
18 changes: 18 additions & 0 deletions src/array.cr
Original file line number Diff line number Diff line change
Expand Up @@ -946,6 +946,24 @@ class Array(T)
self
end

# Returns an `Array` with the first *count* elements removed
# from the original array.
#
# If *count* is bigger than the number of elements in the array, returns an empty array.
#
# ```
# [1, 2, 3, 4, 5, 6].skip(3) # => [4, 5, 6]
# ```
def skip(count : Int) : Array(T)
raise ArgumentError.new("Attempt to skip negative size") if count < 0

new_size = Math.max(size - count, 0)
Array(T).build(new_size) do |buffer|
buffer.copy_from(to_unsafe + count, new_size)
new_size
end
end

# Returns an `Array` with all possible permutations of *size*.
#
# ```
Expand Down

0 comments on commit ed033df

Please sign in to comment.