-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPrintParagraphInNewsPaper.js
More file actions
89 lines (60 loc) · 1.98 KB
/
Copy pathPrintParagraphInNewsPaper.js
File metadata and controls
89 lines (60 loc) · 1.98 KB
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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
// ********* EBay OA Question ************
// ======= Input =======
// paragraphs: an array, each element is an array of words representing a paragraph.
// align: an array of strings "LEFT" or "RIGHT" for each paragraph.
// width: maximum number of characters per line.
// ======= Rules ========
// Build each paragraph by putting words in order separated by space.
// Wrap text so that no line exceeds width.
// Align each line according to align[i].
// Surround the entire result with a * border.
// ====== Output ======
// Array of lines (or a single string) with * border.
function newspaperPage(paragraphs, alignments, width) {
let lines = [];
for (let p = 0; p < paragraphs.length; p++) {
const words = paragraphs[p];
const alignment = alignments[p];
let currentLine = "";
let paraLines = [];
for (let word of words) {
if (currentLine.length === 0) {
currentLine = word;
} else if (currentLine.length + 1 + word.length <= width) {
currentLine += " " + word;
} else {
paraLines.push(currentLine);
currentLine = word;
}
}
if (currentLine.length > 0) paraLines.push(currentLine);
// Apply alignment for this paragraph
paraLines = paraLines.map(line =>
alignment === "RIGHT"
? line.padStart(width, " ")
: line.padEnd(width, " ")
);
lines.push(...paraLines);
}
// Add border
const border = "*".repeat(width + 2);
const result = [border, ...lines.map(line => `*${line}*`), border];
return result; // return array of lines
}
// Example
const paragraphs = [
["This", "is", "first", "paragraph"],
["Second", "one", "goes", "here"]
];
const alignments = ["left", "right"];
const width = 16;
const page = newspaperPage(paragraphs, alignments, width);
// Print properly line by line
page.forEach(line => console.log(line));
// OUTPUT
// ******************
// *This is first *
// *paragraph *
// * Second one*
// * goes here *
// ******************