# 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 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.object ) end end def create_proc(block) lambda do final_alternate_stmt = block && @context.new_block do @context.push( type: 'ReturnStatement', argument: { type: 'CallExpression', callee: @context.ruby_to_js_ast(block), arguments: [] } ) 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.push( type: 'ReturnStatement', argument: { type: 'CallExpression', callee: @context.ruby_to_js_ast(cond_block), arguments: [] } ) 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