class Arboretum::Scandent::Formula

Public Class Methods

new(form_tokens) click to toggle source
# File lib/arboretum/scandent.rb, line 299
def initialize(form_tokens)
  @coefficient = 0
  @intercept = 0
  form_token_types = form_tokens.map {|token| token[0]}
  if form_token_types[0] == :T_KEY_EVEN
    @coefficient = 2
    @intercept = 0
  elsif form_token_types[0] == :T_KEY_ODD
    @coefficient = 2
    @intercept = 1
  else
    term_negative = false
    term_coef = false
    value = 0

    index = 0
    while index < form_tokens.length
      case form_token_types[index]
      when :T_FORM_PLUS
        # Resolve Term
        if term_coef
          @coefficient += value
        else
          @intercept += value
        end
        # Reset with new sign
        term_negative = false
        term_coef = false
        value = 0
      when :T_FORM_MINUS
        # Resolve Term
        if term_coef
          @coefficient += value
        else
          @intercept += value
        end
        # Reset with new sign
        term_negative = true
        term_coef = false
        value = 0
      when :LITERAL_INT
        value = form_tokens[index][1].to_i
        value *= -1 if term_negative
      when :T_FORM_N
        term_coef = true
        value = 1 if value.zero?
      else
        raise InvalidExpressionException.new
      end
      index += 1
    end
    # Resolve one last time
    if term_coef
      @coefficient += value
    else
      @intercept += value
    end
  end
end

Public Instance Methods

to_s() click to toggle source
# File lib/arboretum/scandent.rb, line 359
def to_s
  "#{@coefficient}n#{'+' if @intercept >= 0}#{@intercept}"
end