From 9d812825c9c3dae9c43d194a92ca18afbf2cd8ec Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Johannes=20M=C3=BCller?= Date: Tue, 5 Nov 2024 15:15:03 +0100 Subject: [PATCH] Add new optimized version for `Array#map` based on `Enumerable#map` --- src/array.cr | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) 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. #