Permalink
Browse files

Add some new Enumerable extensions

* Enumerable#sum
* Enumerable#sproduct
  • Loading branch information...
1 parent 9b5ae76 commit b09ada2e6766057dd16256cbeca6a478c641c89c @bbatsov committed Aug 26, 2013
View
@@ -28,6 +28,8 @@ Or install it yourself as:
* [#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)
* [#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)
* [#take_last](http://rdoc.info/github/bbatsov/powerpack/Enumerable#take_last-instance_method)
* [#take_last_while](http://rdoc.info/github/bbatsov/powerpack/Enumerable#take_last_while-instance_method)
* [Hash](http://rdoc.info/github/bbatsov/powerpack/Hash)
@@ -1,5 +1,7 @@
require_relative 'enumerable/drop_last'
require_relative 'enumerable/drop_last_while'
require_relative 'enumerable/several'
+require_relative 'enumerable/sproduct'
+require_relative 'enumerable/sum'
require_relative 'enumerable/take_last'
require_relative 'enumerable/take_last_while'
@@ -0,0 +1,14 @@
+unless Enumerable.method_defined? :sproduct
+ module Enumerable
+ # Multiplies the elements of an enum by invoking their * method.
+ # Most useful for multiplying numbers.
+ #
+ # @example
+ # [1, 2, 3, 4].product #=> 6
+ # [].product #=> nil
+ # [].product(1) #=> 1
+ def sproduct(default = nil)
+ reduce(&:*) || default
+ end
+ end
+end
@@ -0,0 +1,16 @@
+unless Enumerable.method_defined? :sum
+ module Enumerable
+ # Sums up elements of an enum by invoking their + method.
+ # Most useful for summing up numbers.
+ #
+ # @example
+ # [1, 2, 3].sum #=> 6
+ # ["a", "b", "c"].sum #=> "abc"
+ # [[1], [2], [3]].sum #=> [1, 2, 3]
+ # [].sum #=> nil
+ # [].sum(0) #=> 0
+ def sum(default = nil)
+ reduce(&:+) || default
+ end
+ end
+end
@@ -0,0 +1,15 @@
+require 'spec_helper'
+
+describe 'Enumerable#sproduct' do
+ it 'multiply the numbers of an enum' do
+ expect((1..4).sproduct).to eq(24)
+ end
+
+ it 'returns nil when invoked on an empty collection' do
+ expect([].sproduct).to be_nil
+ end
+
+ it 'returns default value when invoked on an empty collection' do
+ expect([].sproduct(0)).to be_zero
+ end
+end
@@ -0,0 +1,15 @@
+require 'spec_helper'
+
+describe 'Enumerable#sum' do
+ it 'sums up the numbers of an enum' do
+ expect((1..3).sum).to eq(6)
+ end
+
+ it 'returns nil when invoked on an empty collection' do
+ expect([].sum).to be_nil
+ end
+
+ it 'returns default value when invoked on an empty collection' do
+ expect([].sum(0)).to be_zero
+ end
+end

0 comments on commit b09ada2

Please sign in to comment.