Skip to content

Commit

Permalink
feature: add map_with_exclusion()
Browse files Browse the repository at this point in the history
  • Loading branch information
mecaneer23 committed Jan 26, 2024
1 parent 76f25be commit abfa8b8
Showing 1 changed file with 25 additions and 3 deletions.
28 changes: 25 additions & 3 deletions src/md_to_py.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,11 @@
Convert a MarkDown table to a formatted Python list.
"""

from typing import Callable, Iterable, Iterator, TypeVar

T = TypeVar("T")
S = TypeVar("S")


def _get_column_widths(
row: str, delimiter: str = "|", strip_spaces: bool = True
Expand Down Expand Up @@ -51,6 +56,23 @@ def _get_column_widths(
return output[:-1]


def map_with_exclusion(
func: Callable[[T], S],
*sequences: Iterable[T],
exclusion: frozenset[int] = frozenset(),
) -> Iterator[S]:
"""
Similar to the built-in `map` function, but allows for
exclusion of certain elements of `seq`.
`exclusion` should be a set of indices to exclude.
"""

for i, arguments in enumerate(zip(*sequences)):
if i not in exclusion:
yield func(*arguments)


def md_table_to_lines(
first_line_idx: int,
last_line_idx: int,
Expand Down Expand Up @@ -136,7 +158,8 @@ def md_table_to_lines(
except FileNotFoundError as err:
raise FileNotFoundError("Markdown file not found.") from err

max_column_lengths = list(map(_get_column_widths, lines))
max_column_lengths = list(zip(*map_with_exclusion(_get_column_widths, lines, exclusion=frozenset((1,)))))


for i, _ in enumerate(lines):
lines[i] = lines[i].replace("- | -", "----").replace(" | ", " " * +2)
Expand All @@ -147,8 +170,7 @@ def md_table_to_lines(


if __name__ == "__main__":
print(_get_column_widths("| Flag | Description |"))
for line in md_table_to_lines(130, 137, "md_to_py.py", ("*",)):
for line in md_table_to_lines(176, 183, "md_to_py.py", ("*",)):
pass
_ = """
| Flag | Description |
Expand Down

0 comments on commit abfa8b8

Please sign in to comment.