Andrey Ermakov

by emilcieslar

JavaScript

// There are two problems, one of them is crucial, second is due to the fact that there was an assumption. Try to solve these problems.
// 1. It won't correctly split lines if there's exactly 25 chars on line because it adds one space at the beginning before the first word.
// 2. It doesn't split sentences with new lines correctly.

// At first, don't tell him those problems, just show him the output of the method and
// see if he can manage to fix it himself.

/**
 Write a simple program that will receive lines of text and will generate output lines of a provided length.
 The output should contain the same words as the input, no words should be removed.
 It should not split any words in the middle. We can assume that no word is longer than the provided length of one line. 
 You should implement this in secret gist and then share the result with us. The returned value should be a string.
 */


// THE FOLLOWING IS HIS SOLUTION WITH TODO COMMENTS FROM ME.

// HOW WOULD YOU UPDATE THE TASK DESCRIPTION SO THAT IT'S MORE CLEAR BUT STILL NOT TOO OBVIOUS?

// first of all, no mentions about input text, 
// so i assume that words in text just separated with one space and no 
// and there are no extraordinary things in there
function printLines(text, length) {
	// TODO: Here, instead of splitting by space, split using the following RegEx: `/\s+/g`.
  // This way, you'll achieve even splitting when text contains new lines.
  const words = text.split(" "); 
  const lines = [];
  let currentLine = "";

  for (const word of words) {
  	// TODO: The following line should be modified as follows:
    // `const newWord = currentLine.length ? currentLine.concat(" ").concat(word) : word;`
    // Otherwise it adds a space at the end of the sentence and last word can fall to the
    // next line if it's equal to length with the space.
    const newWord = currentLine.concat(" ").concat(word);
    if (newWord.length <= length) {
      currentLine = newWord;
    } else {
     ...