JSFiddle - React, Tailwind, and code Playground

by emilcieslar

JavaScript

const textLine = "how are\nyou\n my name\nis Tugkan Cengiz ?"


// Shrinks lines of texts with given length parameter
function shrinkText(w, text) {

  // Creates a word array from given text
  const wordsArray = text.split('\n').join(' ').split(' ').reverse();

  // Creates the output string array
  const textLines = [''];


  // Recursive function definition
  // Iterates over array and push into textLines if necessary
  function recursiveShrink(wordsArray, currentLine) {
    // Return from resursive
    if (wordsArray.length === 0) {
      return '';
    }

    // Get first word
    const currentWord = wordsArray.splice(-1)[0];

    // Check to push
    if (textLines[currentLine].length + currentWord.length + 1 <= w) {
      textLines[currentLine] += `${currentWord} `;
    } else {
      currentLine += 1;
      textLines[currentLine] = `${currentWord} `
    }

    // Iterate recursively
    return recursiveShrink(wordsArray, currentLine);
  }


  // First calling of function
  recursiveShrink(wordsArray, 0);

  // Return textLines
  return textLines;
}


console.log(shrinkText(12, textLine))