# All files / src/generator ternary-expression.js

100% Statements 14/14
100% Branches 0/0
100% Functions 1/1
100% Lines 14/14

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    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
    22x
    22x
    22x
    22x

    22x

    1x
    1x

    1x

    1x

    1x

    1x

    1x

    1x

    1x

     // @flow
    import mapSyntax from "./map-syntax";
    import { generateValueType } from "./utils";
    import mergeBlock from "./merge-block";
    import opcode, { opcodeFromOperator } from "../emitter/opcode";
    import type { GeneratorType } from "./flow/types";

    const generateTernary: GeneratorType = (node, parent) => {
      // TernaryExpression has a simple param layout of 2(TWO) total parameters.
      // It's a single param for the boolean check followed by
      // another param which is a Pair Node containing the 2(TWO) param results of
      // true and false branches.
      // The whole thing is encoded as an implicitly retunred if/then/else block.
      const mapper = mapSyntax(parent);
      const resultPair = node.params[1];

      // Truthy check
      const block = node.params
        .slice(0, 1)
        .map(mapper)
        .reduce(mergeBlock, []);

      // If Opcode
      block.push({
        kind: opcodeFromOperator(node),
        valueType: generateValueType(node),
        params: [],
      });

      // Map the true branch
      block.push.apply(
        block,
        resultPair.params
          .slice(0, 1)
          .map(mapper)
          .reduce(mergeBlock, [])
      );
      block.push({
        kind: opcodeFromOperator({ value: ":", type: "i32" }),
        params: [],
      });

      // Map the false branch
      block.push.apply(
        block,
        resultPair.params
          .slice(-1)
          .map(mapper)
          .reduce(mergeBlock, [])
      );

      // Wrap up the node
      block.push({ kind: opcode.End, params: [] });

      return block;
    };

    export default generateTernary;