Class: Array

Inherits:
Object
  • Object
show all
Defined in:
lib/hashlib.rb

Instance Method Summary collapse

Instance Method Details

#count_distinct(group_by = []) ⇒ Object



183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
# File 'lib/hashlib.rb', line 183

def count_distinct(group_by=[])
  rv = {}

  self.each do |i|
    if i.is_a?(Hash)
      components = group_by
      components = components.collect{|j| i.get(j) }
      components = [*components.first].product([*components.last])

      components.each do |component|
        path = []
        stack = []

        component.compact.each do |c|
          if c.is_a?(Array)
            path += [stack].product(c.flatten).collect{|i| i.flatten }
            stack = []
          else
            stack << c
          end
        end

        path = [component] if path.empty?

        path.each do |parts|
          parts[-1] = :null if parts[-1].nil?
          rv.set(parts, rv.get(parts, 0) + 1)
        end
      end
    end
  end


  sum_children = proc do |sum, key, value|
    if value.is_a?(Hash)
      sum += value.inject(0){|s,(k,v)| sum_children.call(s,k,v) }
    else
      sum += value
    end

    sum
  end

  populate = proc do |rv, key, value|
    i = ({
      :id    => ((key.empty? or key.nil? or key == 'null') ? nil : key),
      :count => (value.is_a?(Hash) ? value.inject(0){|s,(k,v)| sum_children.call(s,k,v) } : value)
    })

    i[:children] = value.inject([]){|s,(k,v)| populate.call(s,k,v) } if value.is_a?(Hash)
    rv << i
    rv
  end

  rv.inject([]){|s,(k,v)| populate.call(s,k,v) }
end