Skip to content

Commit

Permalink
Add StaticArray iterator functions which return a StaticArray too
Browse files Browse the repository at this point in the history
The following fonctions are added to StaticArray. They return a StaticArray.
- map
- map_with_index
- map_with_index!
- reverse
  • Loading branch information
Arthur Poulet committed Sep 26, 2016
1 parent cef67da commit 7d5741a
Show file tree
Hide file tree
Showing 3 changed files with 56 additions and 3 deletions.
2 changes: 1 addition & 1 deletion Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ $(O)/all_spec: deps $(SOURCES) $(SPEC_SOURCES)

$(O)/std_spec: deps $(SOURCES) $(SPEC_SOURCES)
@mkdir -p $(O)
$(BUILD_PATH) ./bin/crystal build $(FLAGS) -o $@ spec/std_spec.cr
$(BUILD_PATH) ./bin/crystal build $(FLAGS) -o $@ spec/std/static_array_spec.cr

$(O)/compiler_spec: deps $(SOURCES) $(SPEC_SOURCES)
@mkdir -p $(O)
Expand Down
34 changes: 32 additions & 2 deletions spec/std/static_array_spec.cr
Original file line number Diff line number Diff line change
Expand Up @@ -101,22 +101,52 @@ 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 "reverse" do
a = StaticArray(Int32, 3).new { |i| i + 1 }
b = a.reverse
b[0].should eq(3)
b[1].should eq(2)
b[2].should eq(1)
b.should be_a(StaticArray(Int32, 3))
a.should_not eq(b)
end

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" do
a = StaticArray(Int32, 3).new { |i| i + 1 }
b = a.map { |i| i + 1 }
b[0].should eq(2)
b[1].should eq(3)
b[2].should eq(4)
b.should be_a(StaticArray(Int32, 3))
a.should_not eq(b)
end

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

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

def map
clone.map! { |e| yield e }
end

def map_with_index!
i = 0
to_unsafe.map!(size) do |e|
i += 1
yield e, i - 1
end
self
end

def map_with_index
clone.map_with_index! do |e, i|
yield e, i
end
end

# Reverses the elements of this array in-place, then returns `self`
#
# ```
Expand All @@ -174,6 +193,10 @@ struct StaticArray(T, N)
self
end

def reverse
clone.reverse!
end

# Returns a slice that points to the elements of this static array.
# Changes made to the returned slice also affect this static array.
#
Expand Down

0 comments on commit 7d5741a

Please sign in to comment.