Skip to content

Commit

Permalink
Optimize Hash#transform_{keys,values} (#14502)
Browse files Browse the repository at this point in the history
  • Loading branch information
jgaskins committed Sep 2, 2024
1 parent c015ff6 commit e6b5b94
Showing 1 changed file with 4 additions and 2 deletions.
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

0 comments on commit e6b5b94

Please sign in to comment.