@@ -236,6 +236,44 @@ struct Slice(T)
236236 @pointer .shuffle!(size, random)
237237 end
238238
239+ # Invokes the given block for each element of `self`, replacing the element
240+ # with the value returned by the block. Returns `self`.
241+ #
242+ # ```
243+ # slice = Slice[1, 2, 3]
244+ # slice.map! { |x| x * x }
245+ # slice # => Slice[1, 4, 9]
246+ # ```
247+ def map !
248+ check_writable
249+
250+ @pointer .map!(size) { |e | yield e }
251+ self
252+ end
253+
254+ # Returns a new slice where elements are mapped by the given block.
255+ #
256+ # ```
257+ # slice = Slice[1, 2.5, "a"]
258+ # slice.map &.to_s # => Slice["1", "2.5", "a"]
259+ # ```
260+ def map (* , read_only = false , & block : T - > U ) forall U
261+ Slice .new(size, read_only: read_only) { |i | yield @pointer [i] }
262+ end
263+
264+ # Like `map!`, but the block gets passed both the element and its index.
265+ def map_with_index !(& block : (T , Int32 ) - > T )
266+ check_writable
267+
268+ @pointer .map_with_index!(size) { |e , i | yield e, i }
269+ self
270+ end
271+
272+ # Like `map`, but the block gets passed both the element and its index.
273+ def map_with_index (* , read_only = false , & block : (T , Int32 ) - > U ) forall U
274+ Slice .new(size, read_only: read_only) { |i | yield @pointer [i], i }
275+ end
276+
239277 def copy_from (source : Pointer (T ), count)
240278 check_writable
241279
0 commit comments