YUKI Hiroshi
null+****@clear*****
Tue Apr 21 21:47:50 JST 2015
YUKI Hiroshi 2015-04-21 21:47:50 +0900 (Tue, 21 Apr 2015) New Revision: 34ce5004bf7086c4265a74d9d64227238ab8aa6f https://github.com/droonga/droonga-engine/commit/34ce5004bf7086c4265a74d9d64227238ab8aa6f Message: Sum all values if both values are hashes and there are only numeric values. 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 } Modified files: lib/droonga/reducer.rb Modified: lib/droonga/reducer.rb (+33 -1) =================================================================== --- lib/droonga/reducer.rb 2015-04-21 21:31:44 +0900 (72156bc) +++ lib/droonga/reducer.rb 2015-04-21 21:47:50 +0900 (1d50b81) @@ -77,7 +77,11 @@ module Droonga 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 @@ -165,5 +169,33 @@ module Droonga 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 -------------- next part -------------- HTML����������������������������... Download