Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Refactor Enumerable#map to delegate to #map_with_index #15210

Merged

Conversation

straight-shoota
Copy link
Member

#map and map_with_index are identical except that the latter also yields an index counter.

But this counter is entirely optional and can be omitted from the block. It's possible to call #map_with_index with exactly the same signature as #map.

["foo", "bar"].map_with_index do |e|
  e.upcase
end # => ["FOO", "BAR"]

["foo", "bar"].map do |e|
  e.upcase
end # => ["FOO", "BAR"]

The implementation of both methods is also pretty much identical, in Enumerable as well as in any including type.
Of course, map_with_index has a counter and yields its value. But LLVM optimization happily removes it when unused.

So I think it makes sense to implement Enumerable#map by delegating to #map_with_index. This embodies the close connection between these two methods.
As a result, including types only need to override #map_with_index with a custom implementation and #map will follow suit.
Including types may still override #map with a custom implementation, of course.

@straight-shoota straight-shoota added this to the 1.15.0 milestone Nov 21, 2024
@straight-shoota straight-shoota merged commit edb8764 into crystal-lang:master Nov 22, 2024
67 of 69 checks passed
@straight-shoota straight-shoota deleted the refactor/enumerable-map branch November 22, 2024 11:15
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants