Permalink
Browse files

Merge pull request #7 from fuadsaud/enumerable-frequency

Add Enumerable#frequency
  • Loading branch information...
2 parents d4dd528 + a910c93 commit 9091159396e6a81c823e7f30a5b097aa6438ac8c @bbatsov committed Aug 29, 2013
View
@@ -27,6 +27,7 @@ Or install it yourself as:
* [Enumerable](http://rdoc.info/github/bbatsov/powerpack/Enumerable)
* [#drop_last](http://rdoc.info/github/bbatsov/powerpack/Enumerable#drop_last-instance_method)
* [#drop_last_while](http://rdoc.info/github/bbatsov/powerpack/Enumerable#drop_last_while-instance_method)
+ * [#frequencies](http://rdoc.info/github/bbatsov/powerpack/Enumerable#frequencies-instance_method)
* [#several?](http://rdoc.info/github/bbatsov/powerpack/Enumerable#several?-instance_method)
* [#sproduct](http://rdoc.info/github/bbatsov/powerpack/Enumerable#sproduct?-instance_method)
* [#sum](http://rdoc.info/github/bbatsov/powerpack/Enumerable#sum-instance_method)
@@ -1,5 +1,6 @@
require_relative 'enumerable/drop_last'
require_relative 'enumerable/drop_last_while'
+require_relative 'enumerable/frequencies'
require_relative 'enumerable/several'
require_relative 'enumerable/sproduct'
require_relative 'enumerable/sum'
@@ -0,0 +1,19 @@
+unless Enumerable.method_defined? :frequencies
+ module Enumerable
+ # Counts the number of ocurrence of items in the enumberable.
+ #
+ # @return [Hash] in the format value => count
+ #
+ # @example
+ # [].frequency # => {}
+ # [1, :symbol, 'string', 3, :symbol, 1].frequency
+ # #=> { 1 => 2, :symbol => 2, 'string' => 1, 3 => 1 }
+ #
+ #
+ def frequencies
+ inject(Hash.new(0)) do |a, e|
+ a.tap { |acc| acc[e] += 1 }
+ end
+ end
+ end
+end
@@ -0,0 +1,20 @@
+require 'spec_helper'
+
+describe 'Enumerable#frequencies' do
+ context 'empty collection' do
+ it 'evaluates to an empty hash' do
+ expect([].frequencies).to eql({})
+ end
+ end
+
+ context 'populated collection' do
+ it 'counts the number of ocurrences and returns a hash in the form value => count' do
+ expect([1, 1, :symbol, 3, 1, :symbol, 'string'].frequencies).to eql(
+ 1 => 3,
+ 3 => 1,
+ 'string' => 1,
+ :symbol => 2
+ )
+ end
+ end
+end

0 comments on commit 9091159

Please sign in to comment.