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

Optimized Array#skip #6946

Merged
merged 1 commit into from
Oct 16, 2018
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/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