Sha256: 1ab8956bc8894213f9063d13dcf2b46859b2a1b27d879a10c22546e7f6065523

Contents?: true

Size: 1.27 KB

Versions: 5

Compression:

Stored size: 1.27 KB

Contents

module Reality
  # @private
  module Util
    module Parse
      module_function

      def scaled_number(str)
        match, amount, scale = */^([0-9.,]+)[[:space:]]*(#{SCALES_REGEXP})?/.match(str)
        match or return nil

        if scale
          number(amount) * fetch_scale(scale)
        else
          number(amount)
        end
      end

      def number(str)
        str = str.gsub(',', '').tr('−', '-')
        case str
        when /^-?\d+$/
          str.to_i
        when /^-?\d+\.\d+$/
          str.to_f
        else
          nil
        end
      end

      private

      module_function

      # See "Short scale": https://en.wikipedia.org/wiki/Long_and_short_scales#Comparison
      SCALES = {
        'million'     => 1_000_000,
        'billion'     => 1_000_000_000,
        'trillion'    => 1_000_000_000_000,
        'quadrillion' => 1_000_000_000_000_000,
        'quintillion' => 1_000_000_000_000_000_000,
        'sextillion'  => 1_000_000_000_000_000_000_000,
        'septillion'  => 1_000_000_000_000_000_000_000_000,
      }
      SCALES_REGEXP = Regexp.union(*SCALES.keys)

      def fetch_scale(str)
        _, res = SCALES.detect{|key, val| str.start_with?(key)}

        res or fail("Scale not found: #{str} for #{self}")
      end
      
    end
  end
end

Version data entries

5 entries across 5 versions & 1 rubygems

Version Path
reality-0.1.0.alpha3 lib/reality/util/parsers.rb
reality-0.1.0.alpha2 lib/reality/util/parsers.rb
reality-0.1.0.alpha lib/reality/util/parsers.rb
reality-0.0.5 lib/reality/util/parsers.rb
reality-0.0.4 lib/reality/util/parsers.rb