Sha256: 9fd980ff5929b780681de48e89bd4a8e3115eeb70af75490b44ed12758abc04b

Contents?: true

Size: 957 Bytes

Versions: 1

Compression:

Stored size: 957 Bytes

Contents

module Unitwise
  module Expression
    class Composer
      attr_reader :terms
      def initialize(terms)
        @terms = terms
      end

      def set
        @set ||= terms.reduce(SignedMultiset.new) do |s, t|
          s.increment({f: t.factor, p: t.prefix_code, a: t.atom_code}, t.exponent); s
        end
      end

      def numerator
        @numerator ||= set.select{|k,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

      def denominator
        @denominator ||= set.select{|k,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

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

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
unitwise-0.3.1 lib/unitwise/expression/composer.rb