diff --git a/src/array.cr b/src/array.cr index f2546aac08b6..29ce219885a3 100644 --- a/src/array.cr +++ b/src/array.cr @@ -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`. # @@ -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. #