#--
# Credit: Malte Milatz
#++

class Integer

  # Calculate the factorial of an integer.
  #
  #   2.factorial  #=> 2
  #   3.factorial  #=> 6
  #   3.factorial  #=> 24
  #

  def factorial
    return 1 if zero?
    f = 1
    2.upto(self) { |n| f *= n }
    f
  end

  #--
  # TODO Pick one of these and deprecate the other. But which?
  #++
  alias_method( :fac, :factorial )
  alias_method( :fact, :factorial )

  #-- OLD CODE
  #def factorial
  #  return 1 if self == 0
  #  #self == 0 ? 1 : ( self * (self-1).factorial )
  #  f = (1..self.abs).inject { |state, item| state * item }
  #  return self < 0 ? -f : f
  #end
  #++

end


#  _____         _
# |_   _|__  ___| |_
#   | |/ _ \/ __| __|
#   | |  __/\__ \ |_
#   |_|\___||___/\__|
#
=begin test

  require 'test/unit'

  class TCInteger < Test::Unit::TestCase

    def test_factorial
      assert_equal(  1, 0.factorial )
      assert_equal(  1, 1.factorial )
      assert_equal(  2, 2.factorial )
      assert_equal(  6, 3.factorial )
      assert_equal( 24, 4.factorial )
    end

  end

=end
