|
1 | | -local function replaceClose(str: string, close: string, replace: string, index: number?): string |
2 | | - local result = "" |
| 1 | +local RESULT_TBL = {} |
| 2 | + |
| 3 | +local function replaceClose( |
| 4 | + str: string, close: string, replace: string, index: number, closeLen: number |
| 5 | +): string |
3 | 6 | local cursor = 1 |
| 7 | + local tblLen = 0 |
| 8 | + |
4 | 9 | while index do |
5 | | - result ..= string.sub(str, cursor, index - 1) .. replace |
6 | | - cursor = index + #close |
7 | | - local nextIndex = string.find(str, close, cursor, true) |
8 | | - index = nextIndex |
| 10 | + tblLen += 1 |
| 11 | + -- not using table.insert because its likely the index would already be allocated |
| 12 | + RESULT_TBL[tblLen] = string.sub(str, cursor, index - 1) |
| 13 | + cursor = index + closeLen |
| 14 | + index = string.find(str, close, cursor, true) |
9 | 15 | end |
10 | | - return result .. string.sub(str, cursor) |
| 16 | + local result = table.concat(RESULT_TBL, replace) |
| 17 | + table.clear(RESULT_TBL) |
| 18 | + |
| 19 | + return `{result}{string.sub(str, cursor)}` |
11 | 20 | end |
12 | 21 |
|
13 | 22 | local function formatter(open: string, close: string, replace: string?): (string) -> string |
| 23 | + local closeLen = #close |
| 24 | + local openLen = #open |
| 25 | + replace = replace or open |
| 26 | + local format = `{open}%*{close}` |
| 27 | + |
14 | 28 | return function(str: string): string |
15 | | - local index = string.find(str, close, #open + 1, true) |
16 | | - if index then |
17 | | - return open .. replaceClose(str, close, replace or open, index) .. close |
18 | | - else |
19 | | - return open .. str .. close |
20 | | - end |
| 29 | + local index = string.find(str, close, openLen + 1, true) |
| 30 | + |
| 31 | + return string.format( |
| 32 | + format, if index then replaceClose(str, close, replace, index, closeLen) else str |
| 33 | + ) |
21 | 34 | end |
22 | 35 | end |
23 | 36 |
|
24 | | -return { |
| 37 | +return table.freeze({ |
25 | 38 | reset = formatter("\x1b[0m", "\x1b[0m"), |
26 | 39 | bold = formatter("\x1b[1m", "\x1b[22m", "\x1b[22m\x1b[1m"), |
27 | 40 | dim = formatter("\x1b[2m", "\x1b[22m", "\x1b[22m\x1b[2m"), |
@@ -67,4 +80,4 @@ return { |
67 | 80 | bgMagentaBright = formatter("\x1b[105m", "\x1b[49m"), |
68 | 81 | bgCyanBright = formatter("\x1b[106m", "\x1b[49m"), |
69 | 82 | bgWhiteBright = formatter("\x1b[107m", "\x1b[49m"), |
70 | | -} |
| 83 | +}) |
0 commit comments