Georgii Sharadze

by emilcieslar

JavaScript

// There was only one issue, noted in the code.

// Show him the output of his current code and ask him whether he's able
// fix that.


function main(text, length) {
  if (!text) {
    return null;
  }

  if (!length || length < 0) {
    return text;
  }

	// TODO: The only issue here is that it doens't apply to multiple line text.
  // It's easily fixed by the following code:
  // `const words = text.split(/\s+/g);`
  const words = text.split(' ');

  let lines = [];
  let line = '';
  words.forEach(el => {
    const newLine = `${line}${el}`;

    if (newLine.length <= length) {
      line = `${newLine} `;
    } else {
      lines.push(line);
      line = `${el} `;
    }
  });
  lines.push(line);

  lines = lines.map(el => el.padEnd(length, ' ').substr(0, length));

  return lines.join('\n');
}



const text = `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. 
It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged.`;

const result = main(text, 25);
console.log(result);