Tell us what’s happening:
I’ve completed the 1st and 3rd part of the problem but for some reason I could not complete the 2nd part and the 4th part of the problem do you have any suggestions on how can I finish the project I don’t know what I’m doing wrong. This is the problem 2. formatText(testText, ‘right’) should produce text with columns justified to the right.
4. formatText(testText, ‘center’) should produce text with columns justified to the center.
Your code so far
function formatText(input, justification) {
// build 2D array and track max width per column
var textArr = [];
var longest = [];
for (var i = 0; i < input.length; i++) {
var cols = input[i].split('$');
textArr.push(cols);
for (var j = 0; j < cols.length; j++) {
if (longest[j] === undefined || cols[j].length > longest[j]) {
longest[j] = cols[j].length;
}
}
}
// pad each field based on justification
for (var i = 0; i < textArr.length; i++) {
for (var j = 0; j < textArr[i].length; j++) {
// drop trailing empty fields (from a $ at end)
if (j === textArr[i].length - 1 && textArr[i][j] === '') {
textArr[i].pop();
break;
}
var word = textArr[i][j];
var fieldWidth = longest[j] + 1; // one extra space
var padCount = fieldWidth - word.length;
// last column loses that extra space
if (j === textArr[i].length - 1) {
padCount--;
}
var padded;
if (justification === 'right') {
padded = ' '.repeat(padCount) + word;
} else if (justification === 'center') {
var left = Math.floor(padCount / 2);
var right = padCount - left;
padded = ' '.repeat(left) + word + ' '.repeat(right);
} else {
// left justify by default
padded = word + ' '.repeat(padCount);
}
textArr[i][j] = padded;
}
// join the columns into one line
textArr[i] = textArr[i].join('');
}
// join all lines with newline
return textArr.join('\n');
}
Your browser information:
User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/138.0.0.0 Safari/537.36 Edg/138.0.0.0
Challenge Information:
Rosetta Code Challenges - Align columns