Sha256: 5676fbbc40fd070e36bb932a11bda4ceba6f789c4b1db0c5e573b93ff7cbfee4

Contents?: true

Size: 1.77 KB

Versions: 3

Compression:

Stored size: 1.77 KB

Contents

# frozen_string_literal: true

module Jsrb
  class CondChain
    def initialize(context, as_expr)
      @context = context
      @as_expr = as_expr
      @stack = []
    end

    def elsif(expr, &block)
      add_case(expr, block)
      self
    end

    def else(&block)
      finalize(block)
    end

    def end
      finalize(nil)
    end
    alias end! end

    private

    def add_case(expr, block)
      @stack << [@context.ruby_to_js_ast(expr), block]
    end

    def finalize(block)
      if_value = @context.new_expression(
        type: 'CallExpression',
        callee: @context.ruby_to_js_ast(create_proc(block)),
        arguments: []
      )
      if @as_expr
        if_value
      else
        @context.push(
          type: 'ExpressionStatement',
          expression: if_value.unwrap!
        )
      end
    end

    def create_proc(block)
      lambda do
        final_alternate_stmt = block && @context.new_block do
          @context.new_expression(
            type: 'CallExpression',
            callee: @context.ruby_to_js_ast(block),
            arguments: []
          ).as_return!
        end
        if_stmt = @stack.reverse.reduce(final_alternate_stmt) do |alternate_stmt, cond_block|
          condition_expr, cond_block = cond_block
          consequent_stmt = @context.new_block do
            @context.new_expression(
              type: 'CallExpression',
              callee: @context.ruby_to_js_ast(cond_block),
              arguments: []
            ).as_return!
          end
          stmt_ast = {
            type: 'IfStatement',
            test: condition_expr,
            consequent: consequent_stmt
          }
          stmt_ast[:alternate] = alternate_stmt if alternate_stmt
          stmt_ast
        end
        @context.push(if_stmt)
      end
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
jsrb-0.2.1 lib/jsrb/cond_chain.rb
jsrb-0.2.0 lib/jsrb/cond_chain.rb
jsrb-0.1.0 lib/jsrb/cond_chain.rb