Tell us what’s happening:
I’m trying to display the aligned text properly for different alignments focusing on displaying columns to the right also the left and center. I formatted the console to the correct alignments but my code still doesn’t pass. Is it possible if you can explain to me where I went wrong so I can figured out how I can correct this issue. Thanks and have a blessed day.
Your code so far
function formatText(text, alignment = 'left') {
// Step 1: Split each line into fields
const lines = text.map(line => line.split('$'));
// Step 2: Determine the maximum width of each column
const maxWidths = lines[0].map((_, colIndex) =>
Math.max(...lines.map(line => (line[colIndex] || '').length))
);
// Step 3: Define alignment functions
// Left justification: pad spaces to the right of the field
const leftJustify = (field, width) => field.padEnd(width, ' ');
// Right justification: pad spaces to the left of the field
const rightJustify = (field, width) => field.padStart(width, ' ');
// Center justification: calculate and pad spaces on both left and right
const centerJustify = (field, width) => {
const totalPadding = width - field.length;
const leftPadding = Math.floor(totalPadding / 2);
const rightPadding = totalPadding - leftPadding;
return ' '.repeat(leftPadding) + field + ' '.repeat(rightPadding);
};
// Step 4: Choose the appropriate alignment function
let justify;
if (alignment === 'left') {
justify = leftJustify;
} else if (alignment === 'right') {
justify = rightJustify;
} else if (alignment === 'center') {
justify = centerJustify;
} else {
throw new Error("Invalid alignment. Choose from 'left', 'right', or 'center'.");
}
// Step 5: Align each field in the columns for every line
const alignedLines = lines.map(line =>
line.map((field, colIndex) => justify(field || '', maxWidths[colIndex])).join(' ')
);
// Step 6: Reassemble the text by joining lines with newline characters
return alignedLines.join('\n');
}
// Test the function with the given text
const testText = [
'Given$a$text$file$of$many$lines',
'where$fields$within$a$line$',
'are$delineated$by$a$single$"dollar"$character',
'write$a$program',
'that$aligns$each$column$of$fields',
'by$ensuring$that$words$in$each$',
'column$are$separated$by$at$least$one$space.',
'Further,$allow$for$each$word$in$a$column$to$be$either$left$',
'justified,$right$justified',
'or$center$justified$within$its$column.'
];
console.log("Left Justified:\n");
console.log(formatText(testText, 'left'));
console.log("\nRight Justified:\n");
console.log(formatText(testText, 'right'));
console.log("\nCenter Justified:\n");
console.log(formatText(testText, 'center'));
Your browser information:
User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/135.0.0.0 Safari/537.36 Edg/135.0.0.0
Challenge Information:
Rosetta Code Challenges - Align columns