Skip to content

Commit

Permalink
Add new optimized version for Array#map based on Enumerable#map
Browse files Browse the repository at this point in the history
  • Loading branch information
straight-shoota committed Nov 5, 2024
1 parent 6d28125 commit 9d81282
Showing 1 changed file with 23 additions and 0 deletions.
23 changes: 23 additions & 0 deletions src/array.cr
Original file line number Diff line number Diff line change
Expand Up @@ -1111,6 +1111,13 @@ class Array(T)
@size = size.to_i
end

# Optimized version of `Enumerable#map`.
def map(& : T -> U) : Array(U) forall U
map_with_index do |item, _|
yield item
end
end

# Modifies `self`, keeping only the elements in the collection for which the
# passed block is truthy. Returns `self`.
#
Expand Down Expand Up @@ -1200,6 +1207,22 @@ class Array(T)
end
end

# Optimized version of `Enumerable#map_with_index`.
#
# Accepts an optional *offset* parameter, which tells it to start counting
# from there.
#
# ```
# gems = ["crystal", "pearl", "diamond"]
# results = gems.map_with_index { |gem, i| "#{i}: #{gem}" }
# results # => ["0: crystal", "1: pearl", "2: diamond"]
# ```
def map_with_index(offset = 0, & : T, Int32 -> U) forall U
ary = Array(U).new(size)
each_with_index(offset) { |e, i| ary << yield e, i }
ary
end

# Returns an `Array` with the first *count* elements removed
# from the original array.
#
Expand Down

0 comments on commit 9d81282

Please sign in to comment.