-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathsolution.js
60 lines (56 loc) · 1.46 KB
/
solution.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
"use strict";
/**
*
* @param {string} line
* @param {string} word
* @param {boolean} considerSpace
* @param {number} maxLineLenght
*/
function isPossibleToConcat(line, word, considerSpace, maxLineLenght) {
if (considerSpace) maxLineLenght--;
return line.length + word.length <= maxLineLenght;
}
/**
*
* @param {[string]} words
* @param {number} maxLineLenght
* @param {number} startIndex
*/
function makeLine(words, maxLineLenght, startIndex) {
let line = "";
let index = startIndex;
while (index < words.length) {
if (
isPossibleToConcat(
line,
words[index],
line.length > 0,
maxLineLenght
)
) {
if (line.length === 0) line += words[index++];
else line += " " + words[index++];
} else break;
}
return { line, stopIndex: index };
}
/**
*
* @param {string} text
* @param {number} maxLineLength
*/
function breakLines(text, maxLineLength) {
const words = text.split(" ");
const lines = [];
let index = 0;
while (index < words.length) {
const { line, stopIndex } = makeLine(words, maxLineLength, index);
if (line.length > 0) lines.push(line);
if (stopIndex === index) break;
index = stopIndex;
}
return (lines.length > 0 && lines) || null;
}
// test
const testString = "the quick brown fox jumps over the lazy dog";
console.log(breakLines(testString, 3));