Skip to content

Commit

Permalink
refactor(wrap-and-indent): splits the algo for readability
Browse files Browse the repository at this point in the history
  • Loading branch information
sverweij committed Jul 8, 2024
1 parent 39b8aa1 commit 0117747
Showing 1 changed file with 34 additions and 30 deletions.
64 changes: 34 additions & 30 deletions src/utl/wrap-and-indent.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -7,40 +7,44 @@ function indentString(pString, pCount) {
}

/**
*
* @param {string} pLine
* @param {number} pMaxWidth
*/
function splitLine(pLine, pMaxWidth) {
const lWords = pLine.split(" ");
const lWrappedLines = [];
let lCurrentLine = "";
let lCurrentWidth = 0;

for (const lWord of lWords) {
if (lCurrentWidth + lWord.length > pMaxWidth) {
lWrappedLines.push(lCurrentLine.trimEnd());
lCurrentLine = "";
lCurrentWidth = 0;
}

if (lCurrentLine) {
lCurrentLine += " ";
lCurrentWidth += 1;
}

lCurrentLine += lWord;
lCurrentWidth += lWord.length;
}

lWrappedLines.push(lCurrentLine.trimEnd());

return lWrappedLines.join("\n");
}

/**
* @param {string} pString - the string to wrap
* @param {number} pMaxWidth - the maximum width of the wrapped string
*/
function wrapString(pString, pMaxWidth) {
const lLines = pString.split(/\r?\n/);

return lLines
.map((pLine) => {
const lWords = pLine.split(" ");
const lWrappedLines = [];
let lCurrentLine = "";
let lCurrentWidth = 0;

for (const lWord of lWords) {
if (lCurrentWidth + lWord.length > pMaxWidth) {
lWrappedLines.push(lCurrentLine.trimEnd());
lCurrentLine = "";
lCurrentWidth = 0;
}

if (lCurrentLine) {
lCurrentLine += " ";
lCurrentWidth += 1;
}

lCurrentLine += lWord;
lCurrentWidth += lWord.length;
}

lWrappedLines.push(lCurrentLine.trimEnd());

return lWrappedLines.join("\n");
})
return pString
.split(/\r?\n/)
.map((pLine) => splitLine(pLine, pMaxWidth))
.join("\n");
}

Expand Down

0 comments on commit 0117747

Please sign in to comment.