My code isn’t working that well. I have gotten every test but 2:
-
- wrap(80) should return 4 lines.
-
- wrap(42) should return 7 lines.
I don’t know what I’m able to do. Please help.
- wrap(42) should return 7 lines.
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));