-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathfullJustify.ts
36 lines (28 loc) · 886 Bytes
/
fullJustify.ts
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
type FullJustify = (words: string[], maxWidth: number) => string[];
/**
* Accepted
*/
export const fullJustify: FullJustify = (words, maxWidth) => {
const result: string[] = [];
let currentLine: string[] = [];
let currentLength = 0;
for (const word of words) {
if (currentLength + word.length + currentLine.length > maxWidth) {
// Distribute spaces for the current line
const totalSpaces = maxWidth - currentLength;
for (let i = 0; i < totalSpaces; i++) {
currentLine[i % (currentLine.length - 1 || 1)] += ' ';
}
result.push(currentLine.join(''));
currentLine = [];
currentLength = 0;
}
currentLine.push(word);
currentLength += word.length;
}
// Handle the last line
result.push(
currentLine.join(' ') + ' '.repeat(maxWidth - currentLength - currentLine.length + 1),
);
return result;
};