Skip to content

Commit

Permalink
feat(strings): add wordWrap*() fns
Browse files Browse the repository at this point in the history
  • Loading branch information
postspectacular committed Jan 8, 2021
1 parent 86fa81a commit 2a283c0
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 0 deletions.
1 change: 1 addition & 0 deletions packages/strings/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,3 +27,4 @@ export * from "./truncate-left";
export * from "./units";
export * from "./uuid";
export * from "./wrap";
export * from "./word-wrap";
43 changes: 43 additions & 0 deletions packages/strings/src/word-wrap.ts
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("");
};

0 comments on commit 2a283c0

Please sign in to comment.