Tell us what’s happening:
Hello I was trying to get the text’s in the right format but the code is still not passing . I was wondering if you could help me in aligning the text’s correctly in alignment with the left, right and center. I don’t think I got in the right text’s.
Your code so far
function formatText(text, alignment = 'left') {
// Split each line into fields
const lines = text.map(line => line.split('$'));
// Determine the maximum width of each column
const maxWidths = lines[0].map((_, colIndex) =>
Math.max(...lines.map(line => (line[colIndex] || '').length))
);
// Define alignment functions
const leftJustify = (field, width) => field.padEnd(width);
const rightJustify = (field, width) => field.padStart(width);
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);
};
// 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'.");
}
// Align each field in the columns
const alignedLines = lines.map(line =>
line.map((field, colIndex) => justify(field, maxWidths[colIndex])).join(' ')
);
return alignedLines.join('\n');
}
// Test the function
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/128.0.0.0 Safari/537.36 Edg/128.0.0.0
Challenge Information:
Rosetta Code Challenges - Align columns