Skip to content

Commit

Permalink
feat: add _get_max_column_widths
Browse files Browse the repository at this point in the history
still doesn't work because _get_delimiter_locations doesn't support stripping spaces
  • Loading branch information
mecaneer23 committed May 20, 2024
1 parent 75b67ab commit 8cccc1c
Showing 1 changed file with 21 additions and 5 deletions.
26 changes: 21 additions & 5 deletions src/md_to_py.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,8 @@
Convert a MarkDown table to a formatted Python list.
"""

from itertools import repeat
from itertools import pairwise, repeat, starmap
from operator import sub
from typing import Callable, Iterable, Iterator, Sequence, TypeVar

T = TypeVar("T")
Expand Down Expand Up @@ -60,25 +61,40 @@ def _get_column_widths(


def _get_delimiter_locations(rows: Sequence[str], delimiter: str = "|") -> Iterator[int]:
"""
Yield an iterator of delimiter locations.
The length of the iterator should be equal to any row.count(delimiter)
"""

if len(delimiter) != 1:
raise ValueError(
f"`delimiter` must be one character, is {len(delimiter)} characters",
)
if delimiter == " ":
raise ValueError("`delimiter` cannot be a space")

remaining_rows = len(rows)
location_number = [0 for _ in range(remaining_rows)]
column = 1
location_number[1] = rows[0].count(delimiter)
for pos in range(len(max(rows, key=len))):
for index, row in enumerate(rows):
if index == 1 or pos > len(row):
continue
if pos == len(row):
remaining_rows -= 1
continue
if pos > len(row):
continue
if row[pos] == delimiter:
location_number[index] += 1
if all(num >= column for num in location_number):
column += 1
yield pos


def _get_max_column_widths():
raise NotImplementedError()
def _get_max_column_widths(rows: Sequence[str], delimiter: str = "|") -> Iterator[int]:
for item in starmap(sub, pairwise(_get_delimiter_locations(rows, delimiter))):
yield -item - 1


def _pad_columns(row: str, widths: tuple[int, ...] | int, delimiter: str = "|") -> str:
Expand Down

0 comments on commit 8cccc1c

Please sign in to comment.