JSFiddle - React, Tailwind, and code Playground
by emilcieslar
TypeScript
const whitespaces = /\s+/g;
const space = " ";
function imperative(len: number, text: string): string[] {
const result: string[] = [];
while (text.length > 0) {
if (text.length <= len) {
result.push(text);
text = "";
} else {
let split = len;
while (text[split] !== space && split > 0) split -= 1;
if (split === 0) throw new Error("Expected to not have super-long words");
result.push(text.substr(0, split));
text = text.substr(split + 1);
}
}
return result;
}
/**
* Bootstrap the algorithms and provide an API
*/
function clean(text: string): string {
return text.replace(whitespaces, space).trim();
}
function layoutLines(lineLength: number, text: string): string[] {
return imperative(lineLength, clean(text));
}
console.log(layoutLines(25, "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.").join('\n'))