Sha256: 6d28901bc58021f1531a7878d938e67e3801e48fada2db3f078fb18e4ada067c

Contents?: true

Size: 1.23 KB

Versions: 3

Compression:

Stored size: 1.23 KB

Contents

# frozen_string_literal: true

class Code
  class Node
    class While < Node
      WHILE_KEYWORD = "while"
      UNTIL_KEYWORD = "until"
      LOOP_KEYWORD = "loop"

      def initialize(parsed)
        return if parsed.blank?

        @operator = parsed.delete(:operator).presence
        @statement = Statement.new(parsed.delete(:statement)) if parsed.key?(
          :statement
        )
        @body = Code.new(parsed.delete(:body).presence)
      end

      def evaluate(**args)
        case @operator
        when WHILE_KEYWORD
          last = Object::Nothing.new

          last = @body&.evaluate(**args) || Object::Nothing.new while (
            @statement&.evaluate(**args) || Object::Nothing.new
          ).truthy?

          last
        when UNTIL_KEYWORD
          last = Object::Nothing.new

          last = @body&.evaluate(**args) || Object::Nothing.new while (
            @statement&.evaluate(**args) || Object::Nothing.new
          ).falsy?

          last
        when LOOP_KEYWORD
          loop { @body&.evaluate(**args) || Object::Nothing.new }
          Object::Nothing.new
        else
          Object::Nothing.new
        end
      rescue Error::Break => e
        e.value || Object::Nothing.new
      end
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
code-ruby-1.1.3 lib/code/node/while.rb
code-ruby-1.1.1 lib/code/node/while.rb
code-ruby-1.1.0 lib/code/node/while.rb