-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Simplify HashHelper::Percentage by removing sum_of_leaves
- Loading branch information
1 parent
7399287
commit 5eaa627
Showing
1 changed file
with
3 additions
and
15 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |