Class: Array

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

Instance Method Summary collapse

Instance Method Details

#count_distinct(group_by = []) ⇒ Object



216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
# File 'lib/hashlib.rb', line 216

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