Class: Keisanjaku::Planner

Inherits:
Object
  • Object
show all
Defined in:
lib/keisanjaku/planner.rb

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(ast, expression: nil) ⇒ Planner

Returns a new instance of Planner.



26
27
28
29
30
31
# File 'lib/keisanjaku/planner.rb', line 26

def initialize(ast, expression: nil)
  @ast = ast
  @expression = expression
  @state = RuleState.new
  @steps = []
end

Class Method Details

.compile(ast, expression: nil) ⇒ Object



65
66
67
# File 'lib/keisanjaku/planner.rb', line 65

def self.compile(ast, expression: nil)
  new(ast, expression: expression).compile
end

Instance Method Details

#compileObject



33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
# File 'lib/keisanjaku/planner.rb', line 33

def compile
  terms, operations = flatten(@ast)
  current_value = term_value(terms.first)
  emit_initial_term(terms.first, chained: !operations.empty?)
  if operations.any?
    ensure_front if @state.face == :back
    ensure_cursor_on_d(current_value) unless cursor_matches_d?(current_value)
  end

  operations.each do |operator, term|
    factor = term_value(term)
    ensure_front
    if operator == :multiply
      emit_multiply(current_value, factor, term)
      current_value *= factor
    else
      emit_divide(current_value, factor, term)
      current_value /= factor
    end
  end

  emit_final_read(current_value, operations.empty? ? terms.first : nil)
  Plan.new(
    expression: @expression,
    steps: @steps,
    true_value: current_value,
    read_scale: final_read_scale(operations.empty? ? terms.first : nil),
    read_value: current_value,
    place_explanation: place_explanation(current_value)
  )
end