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

Optimize Hash#transform_{keys,values} #14502

Merged
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 4 additions & 2 deletions src/hash.cr
Original file line number Diff line number Diff line change
Expand Up @@ -1747,7 +1747,8 @@ class Hash(K, V)
# hash.transform_keys { |key, value| key.to_s * value } # => {"a" => 1, "bb" => 2, "ccc" => 3}
# ```
def transform_keys(& : K, V -> K2) : Hash(K2, V) forall K2
each_with_object({} of K2 => V) do |(key, value), memo|
copy = Hash(K2, V).new(initial_capacity: entries_capacity)
each_with_object(copy) do |(key, value), memo|
memo[yield(key, value)] = value
end
end
Expand All @@ -1762,7 +1763,8 @@ class Hash(K, V)
# hash.transform_values { |value, key| "#{key}#{value}" } # => {:a => "a1", :b => "b2", :c => "c3"}
# ```
def transform_values(& : V, K -> V2) : Hash(K, V2) forall V2
each_with_object({} of K => V2) do |(key, value), memo|
copy = Hash(K, V2).new(initial_capacity: entries_capacity)
each_with_object(copy) do |(key, value), memo|
memo[key] = yield(value, key)
end
end
Expand Down
Loading