Sha256: 945e59bd005707394b95f81378483e06742fa6005c916c3307f6dde6b21fedff

Contents?: true

Size: 1.51 KB

Versions: 10

Compression:

Stored size: 1.51 KB

Contents

# -*- encoding: utf-8 -*-
# -*- frozen_stringing_literal: true -*-
# -*- warn_indent: true -*-

module UnitMeasurements
  class Normalizer
    EXPONENTS_SYMBOLS = {
      "⁰" => "0",
      "¹" => "1",
      "²" => "2",
      "³" => "3",
      "⁴" => "4",
      "⁵" => "5",
      "⁶" => "6",
      "⁷" => "7",
      "⁸" => "8",
      "⁹" => "9",
      "⁺" => "+",
      "⁻" => "-",
    }.freeze

    FRACTIONS_SYMBOLS = {
      "¼"  => "1/4",
      "½"  => "1/2",
      "¾"  => "3/4",
      "⅓"  => "1/3",
      "⅔"  => "2/3",
      "⅕"  => "1/5",
      "⅖"  => "2/5",
      "⅗"  => "3/5",
      "⅘"  => "4/5",
      "⅙"  => "1/6",
      "⅚"  => "5/6",
      "⅐"  => "1/7",
      "⅛"  => "1/8",
      "⅜"  => "3/8",
      "⅝"  => "5/8",
      "⅞"  => "7/8",
      "⅑"  => "1/9",
      "⅒" => "1/10",
      "↉"  => "0/3",
    }.freeze

    EXPONENT_REGEX = /([\d]+[Ee]?[+-]?)(#{EXPONENTS_SYMBOLS.keys.join("|")})/.freeze
    FRACTION_REGEX = /(#{FRACTIONS_SYMBOLS.keys.join("|")})/.freeze
    RATIO_REGEX    = /([\d]+):([\d]+)/.freeze

    class << self
      def normalize(string)
        string.dup.tap do |str|
          if str =~ Regexp.new(EXPONENT_REGEX)
            EXPONENTS_SYMBOLS.each do |search, replace|
              str.gsub!(search) { "#{replace}" }
            end
          end

          str.gsub!(FRACTION_REGEX) { " #{FRACTIONS_SYMBOLS[$1]}" }

          str.gsub!(RATIO_REGEX)    { "#{$1.to_i}/#{$2.to_i}" }

          str.strip!
        end
      end
    end
  end
end

Version data entries

10 entries across 10 versions & 1 rubygems

Version Path
unit_measurements-4.9.0 lib/unit_measurements/normalizer.rb
unit_measurements-4.8.0 lib/unit_measurements/normalizer.rb
unit_measurements-4.7.0 lib/unit_measurements/normalizer.rb
unit_measurements-4.6.0 lib/unit_measurements/normalizer.rb
unit_measurements-4.5.0 lib/unit_measurements/normalizer.rb
unit_measurements-4.4.0 lib/unit_measurements/normalizer.rb
unit_measurements-4.3.0 lib/unit_measurements/normalizer.rb
unit_measurements-4.2.0 lib/unit_measurements/normalizer.rb
unit_measurements-4.1.0 lib/unit_measurements/normalizer.rb
unit_measurements-4.0.0 lib/unit_measurements/normalizer.rb