-
Notifications
You must be signed in to change notification settings - Fork 119
/
Copy pathText Justification.js
61 lines (50 loc) · 1.64 KB
/
Text Justification.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
61
/**
* @param {string[]} words
* @param {number} maxWidth
* @return {string[]}
*/
var fullJustify = function(words, maxWidth) {
if (!words || !words.length) return;
const wordRows = [];
let wordCols = [];
let count = 0;
words.forEach((word, i) => {
if ((count + word.length + wordCols.length) > maxWidth) {
wordRows.push(wordCols);
wordCols = [];
count = 0;
}
wordCols.push(word);
count += word.length;
if (i === words.length - 1) {
wordRows.push(wordCols);
}
});
return wordRows.map((rowWords, i) => justifyText(rowWords, maxWidth, i === wordRows.length - 1));
};
const justifyText = (rowWords, maxWidth, isLastLine) => {
let spaces = maxWidth - rowWords.reduce((acc, curr) => acc + curr.length, 0);
if (rowWords.length === 1) {
return rowWords[0] + ' '.repeat(spaces);
}
if (isLastLine) {
spaces -= rowWords.length - 1
return rowWords.join(' ') + ' '.repeat(spaces);
}
let index = rowWords.length - 1;
let justifiedWord = '';
while (rowWords.length > 0) {
const repeater = Math.floor(spaces / (rowWords.length - 1));
const word = rowWords.pop();
if (index === 0) {
justifiedWord = word + justifiedWord;
} else if (index === 1) {
justifiedWord = ' '.repeat(spaces) + word + justifiedWord;
} else {
justifiedWord = ' '.repeat(repeater) + word + justifiedWord;
}
index--;
spaces -= repeater;
}
return justifiedWord;
}