function wordWrap(text, width = 80) {
if (width <= 0) return text;
const blocks = formatText(text);
const newBlocks = [];
let linePosition = 0;
for (const block of blocks) {
if (linePosition + block.text.length >= width) {
if (block.type === "space") {
newBlocks.push({ type: "space", text: "\n" });
linePosition = 0;
} else {
if (linePosition !== 0) {
newBlocks[newBlocks.length - 1].text = "\n";
}
const newBlock = { ...block };
while (newBlock.text.length >= width) {
newBlocks.push({
type: "text",
text: newBlock.text.substring(0, width)
});
newBlocks.push({ type: "space", text: "\n" });
newBlock.text = newBlock.text.substring(width);
}
newBlocks.push(newBlock);
linePosition = newBlock.text.length;
}
} else {
if (block.type === "space" && linePosition === 0) {
continue;
}
newBlocks.push(block);
linePosition += block.text.length;
}
}
return newBlocks.map((block) => block.text).join("");
}