JSFiddle - React, Tailwind, and code Playground

by emilcieslar

TypeScript

function last < T > (arr: T[]) {
  return arr[arr.length - 1];
}

function splitByMaximalSymbols(maxSymbolsPerLine: number, inputText: string) {
  const splitText = inputText.split(" ");
  const result: string[][] = [
    []
  ];

  let concatenateIterationCharactersCount = 0;

  splitText.forEach((word) => {
    const newConcatenateIterationCharactersCount = concatenateIterationCharactersCount + word.length;
    if (newConcatenateIterationCharactersCount <= maxSymbolsPerLine) {
      concatenateIterationCharactersCount = newConcatenateIterationCharactersCount;
      last(result).push(word);
      return;
    }
    concatenateIterationCharactersCount = word.length;
    result.push([word]);
  });

  return result;
}

console.log(splitByMaximalSymbols(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(':"|}"'));