-
-
Notifications
You must be signed in to change notification settings - Fork 151
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
86fa81a
commit 2a283c0
Showing
2 changed files
with
44 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,43 @@ | ||
import { lengthAnsi } from "./ansi"; | ||
|
||
export const wordWrap = (str: string, lineWidth?: number) => | ||
wordWrapLines(str, lineWidth).join("\n"); | ||
|
||
export const wordWrapLines = (str: string, lineWidth = 80) => { | ||
const res: string[] = []; | ||
for (let line of str.split("\n")) { | ||
if (!line.length) { | ||
res.push(""); | ||
continue; | ||
} | ||
wordWrapLine(line, lineWidth, res); | ||
} | ||
return res; | ||
}; | ||
|
||
export const wordWrapLine = ( | ||
line: string, | ||
lineWidth = 80, | ||
acc: string[] = [] | ||
) => { | ||
let ln = 0; | ||
let curr: string[] = []; | ||
for (let w of line.split(" ")) { | ||
const l = lengthAnsi(w) + (ln > 0 ? 1 : 0); | ||
if (ln + l <= lineWidth) { | ||
curr.push(w, " "); | ||
ln += l; | ||
} else { | ||
acc.push(trimLine(curr)); | ||
curr = [w, " "]; | ||
ln = l; | ||
} | ||
} | ||
ln && acc.push(trimLine(curr)); | ||
return acc; | ||
}; | ||
|
||
const trimLine = (x: string[]) => { | ||
/^\s+$/.test(x[x.length - 1]) && x.pop(); | ||
return x.join(""); | ||
}; |