Navigation Menu

Skip to content

Commit

Permalink
Sum all values if both values are hashes and there are only numeric v…
Browse files Browse the repository at this point in the history
…alues.

ex.:
  x = { a: 0, b: 1, c: 2 }
  y = { a: 1, b: 2, c: 3, d: 4 }
   => { a: 1, b: 3, c: 5, d: 4 }
  • Loading branch information
piroor committed Apr 21, 2015
1 parent b38cf1a commit 34ce500
Showing 1 changed file with 33 additions and 1 deletion.
34 changes: 33 additions & 1 deletion lib/droonga/reducer.rb
Expand Up @@ -77,7 +77,11 @@ def sum(x, y)
return x || y if x.nil? or y.nil?

if x.is_a?(Hash) and y.is_a?(Hash)
x.merge(y)
if number_hash?(x) and number_hash?(y)
sum_number_hashes(x, y)
else
x.merge(y)
end
else
x + y
end
Expand Down Expand Up @@ -165,5 +169,33 @@ def unify_by_key!(base_items, unified_items, options={})
end
end
end

def number_hash?(hash)
return false unless hash.is_a?(Hash)
hash.values.all? do |value|
case value
when Numeric
true
when Hash
number_hash?(value)
else
false
end
end
end

def sum_number_hashes(x, y)
sum = {}
(x.keys + y.keys).each do |key|
x_value = x[key]
y_value = y[key]
if number_hash?(x_value) and number_hash?(y_value)
sum[key] = sum_number_hashes(x_value, y_value)
else
sum[key] = (x_value || 0) + (y_value || 0)
end
end
sum
end
end
end

0 comments on commit 34ce500

Please sign in to comment.