Sha256: c8a493b224be7408f1bc62b94bf0cbc004d0604b72182766742bdec2535b9d5d

Contents?: true

Size: 1.12 KB

Versions: 2

Compression:

Stored size: 1.12 KB

Contents

require_relative 'batch'
require_relative 'response'

module Command
  class If
    def initialize(condition_statement)
      @condition_statement = condition_statement
      @body_statements = []
      @else_statements = []
      @in_else = false
    end

    def else!
      raise ArgumentError, 'unexpected else statement' if @in_else
      @in_else = true
    end

    def add_statement(statement)
      if @in_else
        @else_statements << statement
      else
        @body_statements << statement
      end
    end

    def execute(compass, location, tokens)
      response = @condition_statement.execute(compass, location, tokens)
      operations_count = response.operations_count
      statements = response.return_value ? @body_statements : @else_statements
      batch_response = Batch.new(statements).execute(
        response.compass, response.location, response.tokens
      )

      Response.new(
        compass: batch_response.compass,
        location: batch_response.location,
        operations_count: response.operations_count + batch_response.operations_count,
        tokens: batch_response.tokens
      )
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
karel-interpreter-0.2.0 lib/karel/command/if.rb
karel-interpreter-0.1.0 lib/karel/command/if.rb