def _translate_ternary()

in o2a/o2a_libs/src/o2a_lib/el_parser.py [0:0]


def _translate_ternary(tree: Tree, functions_module: str) -> Optional[str]:
    """
    Translates ternary expression.
    """
    if tree.data == "expression" and "ternary" in [ch.data for ch in tree.children]:
        # Case of `f() ? true : false`
        condition, ternary = tree.children
        _, if_true, _, if_false = ternary.children
        translation = (
            f"{_translate_el(if_true, functions_module)} if "
            f"{_translate_el(condition, functions_module)} else {_translate_el(if_false, functions_module)}"
        )
        return translation

    if tree.data == "expression1" and "ternary" in [ch.data for ch in tree.children[-1].children]:
        # Case of `x op y ? true : false`
        first = _translate_el(tree.children[0], functions_module)
        operator = _translate_el(tree.children[1], functions_module)

        # expression | ternary
        expression, ternary = tree.children[2].children

        # ? | expression | : | expression
        _, if_true, _, if_false = ternary.children

        second = _translate_el(expression)

        condition = f"{first}{operator}{second}"
        translation = (
            f"{_translate_el(if_true, functions_module)} if "
            f"{condition} else {_translate_el(if_false, functions_module)}"
        )
        return translation

    return None