Rosetta Code Challenges - Word Wrap

My code isn’t working that well. I have gotten every test but 2:

    1. wrap(80) should return 4 lines.
    1. wrap(42) should return 7 lines.
      I don’t know what I’m able to do. Please help.
function wrap(text, limit) {
  const words = text.split(' ');
  let wrappedText = '';
  let currentLine = '';

  for (const word of words) {
    // Check if adding the next word exceeds the limit
    if (currentLine.length + word.length + (currentLine.length > 0 ? 1 : 0) > limit) {
      // If it does, add the current line to wrappedText and start a new line
      wrappedText += currentLine + '\n'; // Add the current line
      currentLine = word; // Start a new line with the current word
    } else {
      // Otherwise, add the word to the current line
      currentLine += (currentLine.length > 0 ? ' ' : '') + word;
    }
  }

  // Add the last line if it's not empty
  if (currentLine.length > 0) {
    wrappedText += currentLine; // Add the last line
  }

  // Split into lines and filter out empty lines
  const lines = wrappedText.split('\n').filter(line => line.trim() !== '');

  // Return the wrapped text
  return lines.join('\n');
}

// Sample text
const text = 'Wrap text using a more sophisticated algorithm such as the Knuth and Plass TeX algorithm. If your language provides this, you get easy extra credit, but you must reference documentation indicating that the algorithm is something better than a simple minimum length algorithm.';

// Testing the function
console.log('Wrapped text (limit 80):');
console.log(wrap(text, 80));
console.log('---');
console.log('Wrapped text (limit 42):');
console.log(wrap(text, 42));

can you explain what is your approach to solving the algorithm?

I tried to arrange the text into lines that go to a specified character limit, dealing with both long words and line breaks well. I did not do that well, being that this post is here.

Sorry for the late response, it was the holidays.

it looks like the string in the tests already contains new line characters. I am creating a bug fix for that