Sha256: d79b74416b45ec4178be9897c984d0abc394c41fc7fed89515bff543cd33d35e

Contents?: true

Size: 1.56 KB

Versions: 4

Compression:

Stored size: 1.56 KB

Contents

# frozen_string_literal: true

##
# Usage example:
#
#   result = ConvenientService::Examples::Standard::Factorial::Services::Calculate.result(number: 10)
#
module ConvenientService
  module Examples
    module Standard
      class Factorial
        module Services
          class Calculate
            include ConvenientService::Standard::Config
            include ConvenientService::AwesomePrintInspect::Config

            attr_reader :number, :timeout_seconds

            def initialize(number:, timeout_seconds: 10)
              @number = number
              @timeout_seconds = timeout_seconds
            end

            def result
              return error("is `nil`") if number.nil?
              return error("is NOT an integer") unless number.instance_of?(::Integer)
              return error("is lower than `0`") if number < 0

              return error("Timeout (`#{timeout_seconds}` seconds) is exceeded for `#{number}`") if factorial.timeout?

              success(factorial: factorial.value)
            end

            private

            def factorial
              @factorial ||= Utils::Timeout.with_timeout(timeout_seconds) { calculate_factorial }
            end

            ##
            # @internal
            #   NOTE: What is a Factorial?
            #   - https://en.wikipedia.org/wiki/Factorial
            #
            def calculate_factorial
              return 1 if [0, 1].include?(number)

              1.upto(number).reduce(1) { |prev_value, next_value| prev_value * next_value }
            end
          end
        end
      end
    end
  end
end

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
convenient_service-0.17.0 lib/convenient_service/examples/standard/factorial/services/calculate.rb
convenient_service-0.16.0 lib/convenient_service/examples/standard/factorial/services/calculate.rb
convenient_service-0.15.0 lib/convenient_service/examples/standard/factorial/services/calculate.rb
convenient_service-0.14.0 lib/convenient_service/examples/standard/factorial/services/calculate.rb