refactor: improve code readability
This commit is contained in:
@@ -53,11 +53,13 @@ class FiftyOhmHtmlRenderer(HtmlRenderer):
|
|||||||
return f"<u>{self.render_inner(token)}</u>"
|
return f"<u>{self.render_inner(token)}</u>"
|
||||||
|
|
||||||
@classmethod
|
@classmethod
|
||||||
def render_unit(cls, token):
|
def render_unit(cls, token: Unit):
|
||||||
unit = token.prefix + cls.format_unit(token.unit)
|
unit = token.prefix + cls.convert_unit_helper(token.unit)
|
||||||
if token.unit in ["°", "%"]:
|
if token.unit in ["°", "%"]:
|
||||||
|
# Special cases with no space between value and unit.
|
||||||
return f"{token.value}{unit}"
|
return f"{token.value}{unit}"
|
||||||
else:
|
else:
|
||||||
|
# Default case is rendered with a narrow no-break space.
|
||||||
return f"{token.value} {unit}"
|
return f"{token.value} {unit}"
|
||||||
|
|
||||||
units = {
|
units = {
|
||||||
@@ -65,7 +67,11 @@ class FiftyOhmHtmlRenderer(HtmlRenderer):
|
|||||||
}
|
}
|
||||||
|
|
||||||
@classmethod
|
@classmethod
|
||||||
def format_unit(cls, unit):
|
def convert_unit_helper(cls, unit: str) -> str:
|
||||||
|
"""Converts human-typable units to their preferred representation.
|
||||||
|
|
||||||
|
:param str unit: The unit to convert
|
||||||
|
"""
|
||||||
if unit in cls.units.keys():
|
if unit in cls.units.keys():
|
||||||
return cls.units[unit]
|
return cls.units[unit]
|
||||||
else:
|
else:
|
||||||
|
|||||||
+10
-6
@@ -35,17 +35,21 @@ class Unit(SpanToken):
|
|||||||
prefixes = ["p", "n", "μ", "m", "k", "M", "G"]
|
prefixes = ["p", "n", "μ", "m", "k", "M", "G"]
|
||||||
|
|
||||||
pattern = re.compile(
|
pattern = re.compile(
|
||||||
r"([0-9,]+) ?("
|
r"(?P<value>[0-9,]+) ?(?P<prefix>"
|
||||||
# Group all prefixes together in a capture group
|
# Group all prefixes together in a capture group
|
||||||
# Empty string at end of list is required so the group always exists in the resulting match
|
# Empty string at end of list is required so the group always exists in the resulting match
|
||||||
+ "|".join(prefixes + [""])
|
+ "|".join(prefixes + [""])
|
||||||
+ ")("
|
+ ")(?P<unit>"
|
||||||
# Group all units together in a capture group.
|
# Group all units together in a capture group.
|
||||||
+ "|".join(units)
|
+ "|".join(units)
|
||||||
+ r")(?!\w)"
|
+ r")(?!\w)"
|
||||||
)
|
)
|
||||||
|
|
||||||
def __init__(self, match):
|
value: str
|
||||||
self.value = match.group(1)
|
prefix: str
|
||||||
self.prefix = match.group(2)
|
unit: str
|
||||||
self.unit = match.group(3)
|
|
||||||
|
def __init__(self, match: re.Match):
|
||||||
|
self.value = match.group("value")
|
||||||
|
self.prefix = match.group("prefix") or ""
|
||||||
|
self.unit = match.group("unit")
|
||||||
|
|||||||
Reference in New Issue
Block a user