Class: Unitwise::Expression::Composer

Inherits:
Object
  • Object
show all
Defined in:
lib/unitwise/expression/composer.rb

Overview

Composer creates string expressions for arrays of terms, following UCUM’s conventions.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(terms, mode) ⇒ Composer

Returns a new instance of Composer.



7
8
9
10
# File 'lib/unitwise/expression/composer.rb', line 7

def initialize(terms, mode)
  @terms  = terms
  @mode = mode || :primary_code
end

Instance Attribute Details

#modeObject (readonly)

Returns the value of attribute mode.



6
7
8
# File 'lib/unitwise/expression/composer.rb', line 6

def mode
  @mode
end

#termsObject (readonly)

Returns the value of attribute terms.



6
7
8
# File 'lib/unitwise/expression/composer.rb', line 6

def terms
  @terms
end

Instance Method Details

#denominatorObject



27
28
29
30
31
# File 'lib/unitwise/expression/composer.rb', line 27

def denominator
  @denominator ||= set.select{ |_, v| v < 0 }.map do |k, v|
    "#{ k[:f] if k[:f] != 1 }#{ k[:p] }#{ k[:a] }#{ -v if v != -1 }"
  end.select { |t| !t.empty? }.join('.')
end

#expressionObject



33
34
35
36
37
38
# File 'lib/unitwise/expression/composer.rb', line 33

def expression
  @expression = []
  @expression << (numerator.empty? ? '1' : numerator)
  (@expression << denominator) unless denominator.empty?
  @expression.join('/')
end

#numeratorObject



21
22
23
24
25
# File 'lib/unitwise/expression/composer.rb', line 21

def numerator
  @numerator ||= set.select{ |_, v| v > 0 }.map do |k, v|
    "#{ k[:f] if k[:f] != 1 }#{ k[:p] }#{ k[:a] }#{ v if v != 1 }"
  end.select { |t| !t.empty? }.join('.')
end

#setObject



12
13
14
15
16
17
18
19
# File 'lib/unitwise/expression/composer.rb', line 12

def set
  @set ||= terms.reduce(SignedMultiset.new) do |s, t|
    identifier = { :f => t.factor,
                   :p => (t.prefix.to_s(mode) if t.prefix),
                   :a => (t.atom.to_s(mode) if t.atom) }
    s.increment(identifier, t.exponent); s
  end
end