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

StaticArray improvements (map_with_index!) #3356

Closed
Closed
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: 11 additions & 2 deletions spec/std/static_array_spec.cr
Original file line number Diff line number Diff line change
Expand Up @@ -101,22 +101,31 @@ describe "StaticArray" do
end
end

it "reverse" do
it "reverse!" do
a = StaticArray(Int32, 3).new { |i| i + 1 }
a.reverse!
a[0].should eq(3)
a[1].should eq(2)
a[2].should eq(1)
end

it "maps!" do
it "map!" do
a = StaticArray(Int32, 3).new { |i| i + 1 }
a.map! { |i| i + 1 }
a[0].should eq(2)
a[1].should eq(3)
a[2].should eq(4)
end

it "map_with_index!" do
a = StaticArray(Int32, 3).new { |i| i + 1 }
a.map_with_index! { |e, i| i * 2 }
a[0].should eq(0)
a[1].should eq(2)
a[2].should eq(4)
a.should be_a(StaticArray(Int32, 3))
end

it "updates value" do
a = StaticArray(Int32, 3).new { |i| i + 1 }
a.update(1) { |x| x * 2 }
Expand Down
11 changes: 11 additions & 0 deletions src/static_array.cr
Original file line number Diff line number Diff line change
Expand Up @@ -163,6 +163,17 @@ struct StaticArray(T, N)
self
end

# Like `map`, but the block gets passed both the element and its index.
def map_with_index!
i = 0
to_unsafe.map!(size) do |e|
res = yield e, i
i += 1
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Incrementing i after yield would allow to drop i - 1 part which seems bit odd... just a thought :)

Copy link
Contributor Author

@Nephos Nephos Sep 26, 2016

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

map! do |e|
  res = yield e, i
  i += 1
  res
end

?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

done

res
end
self
end

# Reverses the elements of this array in-place, then returns `self`
#
# ```
Expand Down