From 710e297f4a42e78d0217de57be2e004880999d32 Mon Sep 17 00:00:00 2001 From: Arthur Poulet Date: Mon, 26 Sep 2016 17:20:17 +0100 Subject: [PATCH] Add StaticArray.map_with_index! --- spec/std/static_array_spec.cr | 13 +++++++++++-- src/static_array.cr | 11 +++++++++++ 2 files changed, 22 insertions(+), 2 deletions(-) diff --git a/spec/std/static_array_spec.cr b/spec/std/static_array_spec.cr index 0d6f89f27f29..380de48eceac 100644 --- a/spec/std/static_array_spec.cr +++ b/spec/std/static_array_spec.cr @@ -101,7 +101,7 @@ 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) @@ -109,7 +109,7 @@ describe "StaticArray" do 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) @@ -117,6 +117,15 @@ describe "StaticArray" do 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 } diff --git a/src/static_array.cr b/src/static_array.cr index 28eb4b8e5834..1096ba25c6cb 100644 --- a/src/static_array.cr +++ b/src/static_array.cr @@ -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 + res + end + self + end + # Reverses the elements of this array in-place, then returns `self` # # ```