Skip to content

Commit

Permalink
Simplify HashHelper::Percentage by removing sum_of_leaves
Browse files Browse the repository at this point in the history
  • Loading branch information
Tobias-Knudsen committed Dec 17, 2024
1 parent 7399287 commit 5eaa627
Showing 1 changed file with 3 additions and 15 deletions.
18 changes: 3 additions & 15 deletions lib/hash_helper/percentage.rb
Original file line number Diff line number Diff line change
@@ -1,31 +1,19 @@
module HashHelper
module Percentage
def transform_values_to_percentages(precision: nil)
total_sum = sum_of_leaves
total_sum = deep_sum
return self if total_sum.zero?

transform_values do |v|
if v.is_a?(Hash)
v.transform_values_to_percentages(precision: precision)
elsif v.is_a?(Numeric)
percentage = (v.to_f / total_sum * 100)
percentage = (v.to_f / deep_sum * 100)
precision ? percentage.round(precision) : percentage
else
v # Preserve non-numeric and nil values
v
end
end
end

def sum_of_leaves
sum do |_k, v|
if v.is_a?(Hash)
v.sum_of_leaves
elsif v.is_a?(Numeric)
v.to_f
else
0.0
end
end.to_f
end
end
end

0 comments on commit 5eaa627

Please sign in to comment.