Class: Seimi::Formula::Parser

Inherits:
Object
  • Object
show all
Defined in:
lib/seimi/formula/parser.rb

Constant Summary collapse

UPPER =
/[A-Z]/.freeze
LOWER =
/[a-z]/.freeze
DIGIT =
/[0-9]/.freeze
SUPERSCRIPT_DIGITS =
{
  "" => "0", "¹" => "1", "²" => "2", "³" => "3", "" => "4",
  "" => "5", "" => "6", "" => "7", "" => "8", "" => "9"
}.freeze
SUPERSCRIPT_SIGNS =
{ "" => "+", "" => "-" }.freeze

Instance Method Summary collapse

Constructor Details

#initialize(source) ⇒ Parser

Returns a new instance of Parser.



15
16
17
# File 'lib/seimi/formula/parser.rb', line 15

def initialize(source)
  @source = String(source).strip
end

Instance Method Details

#parseObject



19
20
21
22
23
24
25
26
27
28
29
30
31
32
# File 'lib/seimi/formula/parser.rb', line 19

def parse
  body, charge = split_charge(@source)
  parsed = split_hydrate_segments(body).each_with_index.map do |segment, index|
    parse_segment(segment, hydrate: index.positive?)
  end

  Formula.new(
    @source,
    compact_composition(parsed, :composition),
    compact_composition(parsed, :balance_composition),
    compact_components(parsed.flat_map { |item| item[:components] }),
    charge
  )
end