refactor: combine code more efficiently

This commit is contained in:
Daylin Morgan 2023-09-14 22:35:19 -05:00
parent 29a4de39d6
commit 5564fdb18a
Signed by: daylin
GPG key ID: C1E52E7DD81DF79F
2 changed files with 11 additions and 8 deletions

View file

@ -15,7 +15,6 @@ let
"reverse": "7", "reverse": "7",
"conceal": "8", "conceal": "8",
"strike": "9", "strike": "9",
}.newStringTable(modeCaseInsensitive) }.newStringTable(modeCaseInsensitive)
bbColors* = { bbColors* = {
@ -31,6 +30,7 @@ let
proc toAnsiCode*(s: string): string = proc toAnsiCode*(s: string): string =
var var
codes: seq[string]
styles: seq[string] styles: seq[string]
bgStyle: string bgStyle: string
if " on " in s or s.startswith("on"): if " on " in s or s.startswith("on"):
@ -41,11 +41,14 @@ proc toAnsiCode*(s: string): string =
styles = s.splitWhitespace() styles = s.splitWhitespace()
for style in styles: for style in styles:
if style in bbStyles: if style in bbStyles:
result.add "\e[" & bbStyles[style] & "m" codes.add bbStyles[style]
elif style in bbColors: elif style in bbColors:
result.add "\e[3" & bbColors[style] & "m" codes.add "3" & bbColors[style]
if bgStyle in bbColors:
codes.add "4" & bbColors[bgStyle]
let style = bgStyle if codes.len > 0:
if style in bbColors: result.add "\e["
result.add "\e[4" & bbColors[style] & "m" result.add codes.join ";"
result.add "m"

View file

@ -17,7 +17,7 @@ suite "basic":
bbCheck "[red]red text", "\e[31mred text\e[0m" bbCheck "[red]red text", "\e[31mred text\e[0m"
bbCheck "[red]Red Text", "\e[31mRed Text\e[0m" bbCheck "[red]Red Text", "\e[31mRed Text\e[0m"
bbCheck "[yellow]Yellow Text","\e[33mYellow Text\e[0m" bbCheck "[yellow]Yellow Text","\e[33mYellow Text\e[0m"
bbCheck "[bold red]Bold Red Text", "\e[1m\e[31mBold Red Text\e[0m" bbCheck "[bold red]Bold Red Text", "\e[1;31mBold Red Text\e[0m"
test "closing": test "closing":
bbCheck "[bold]Bold[red] Bold Red[/red] Bold Only", bbCheck "[bold]Bold[red] Bold Red[/red] Bold Only",
@ -40,7 +40,7 @@ suite "basic":
bbCheck "[red]Red Text[/]\nNext Line", "\e[31mRed Text\e[0m\nNext Line" bbCheck "[red]Red Text[/]\nNext Line", "\e[31mRed Text\e[0m\nNext Line"
test "on color": test "on color":
bbCheck "[red on yellow]Red on Yellow", "\e[31m\e[43mRed on Yellow\e[0m" bbCheck "[red on yellow]Red on Yellow", "\e[31;43mRed on Yellow\e[0m"
test "concat-ops": test "concat-ops":
check "[red]RED[/]".bb & " plain string" == "[red]RED[/] plain string".bb check "[red]RED[/]".bb & " plain string" == "[red]RED[/] plain string".bb