Class: Array

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

Instance Method Summary collapse

Instance Method Details

#count_distinct(group_by = []) ⇒ Object



306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
# File 'lib/hashlib.rb', line 306

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