What is your hint or solution suggestion?
Summary
This solution uses a separate function to calculate each width of the columns according to the maximum word length in each column.
const testArr = [
"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."
];
let formatText = (input, justification) => {
// Assuming here that any leading or trailing delimiters are wanted.
input = input.map(row => row.split('$'));
const COLUMNWIDTH = getColumnWidths(input);
let justifiedText = '';
// Iterate through each row and add padding according to each column width.
for(let row in input) {
if(row > 0) {
justifiedText += '\n';
}
for(let column in input[row]) {
const WORD = input[row][column];
const PADDING = 1 + COLUMNWIDTH[column] - WORD.length;
if(justification === 'left') {
justifiedText += WORD + ' '.repeat(PADDING) + ' ';
}
else if (justification === 'right') {
justifiedText += ' '.repeat(PADDING - 1) + WORD + ' ';
}
else if (justification === 'center') {
justifiedText += ' '.repeat(Math.floor(PADDING / 2)) + WORD + ' '.repeat(Math.ceil(PADDING / 2)) + ' ';
}
}
}
return justifiedText;
}
const getColumnWidths = (textArray) => {
let columnWidths = [];
textArray.forEach(
row => {
if (row.length > columnWidths.length) {
columnWidths = columnWidths.concat(
new Array(row.length - columnWidths.length).fill(0)
);
}
for(let column in row) {
if(row[column].length > columnWidths[column]) {
columnWidths[column] = row[column].length;
}
}
}
)
return columnWidths;
}
Challenge: Align columns
Link to the challenge: