• Skynet0's avatar
    Code · 9f5fe1b7
    Skynet0 authored
    9f5fe1b7
str_helpers.py 2.2 KB
from typing import Callable, Dict, List, Literal, Text


def str_matrix_to_text(
    matrix: List[List[str]],
    padding: Dict[str, str] = None,
    align_type: Literal["left", "center", "right"] = "center",
) -> Text:
    """Convert a matrix of strings to an aligned multiline string.

    Args:
        str_grid (List[List[str]]): 2D string matrix
        padding (Dict[str, str], optional): Dictionary containing a mapping from
            cell contents to padding strs.
        align_type (Literal["left", "center", "right"], optional): Type of alignment.
            Defaults to "center".

    Returns:
        Text: Printable multiline string
    """
    align_fn: Callable[[str, int, str], str] = {
        "left": str.ljust,
        "center": str.center,
        "right": str.rjust,
    }[align_type]

    if padding is None:
        padding = {}
    max_sym_len = max([max([len(s) for s in r]) for r in matrix])

    return "\n".join(
        [
            "".join([align_fn(s, max_sym_len, padding.get(s, " ")) for s in r])
            for r in matrix
        ]
    )


def ortho_dirs_sym(
    N: bool = False, S: bool = False, W: bool = False, E: bool = False
) -> str:
    """Converts boolean edges that connect cell centers to a Unicode symbol.

    Args:
        N (bool, optional): Presence of edge exiting to the north (up)
        S (bool, optional): Presence of edge exiting to the south (down)
        W (bool, optional): Presence of edge exiting to the west (left)
        E (bool, optional): Presence of edge exiting to the east (right)

    Returns:
        str: Unicode symbol for given directions
    """
    idx = sum([v * 2 ** i for i, v in enumerate([N, S, W, E])])
    # There have to be SO MANY BETTER WAYS TO DO THIS
    symbols = [
        " ",  # ----
        chr(0x2575),  # ---U
        chr(0x2577),  # --D-
        chr(0x2502),  # --DU
        chr(0x2574),  # -L--
        chr(0x2518),  # -L-U
        chr(0x2510),  # -LD-
        chr(0x2524),  # -LDU
        chr(0x2576),  # R---
        chr(0x2514),  # R--U
        chr(0x250C),  # R-D-
        chr(0x251C),  # R-DU
        chr(0x2500),  # RL--
        chr(0x2534),  # RL-U
        chr(0x252C),  # RLD-
        chr(0x253C),  # RLDU
    ]

    return symbols[idx]