Tell us what’s happening:
My output appears to be correct, yet my code doesn’t pass test 2, 3, or 4. I’ve looked at other questions, but with no known correct output, I can’t check my output against it. I previously tried to get help, but got no response.
Your code so far
function formatText(input, justification) {
let length = [];
let result = input.map((line) => {
line = line.split('$').filter((str, idx) => {
if(idx > length.length - 1) {
length.push(0);
}
length[idx] = Math.max(str.length, length[idx]);
if(str !== '') {
return str;
}
});
return line;
}).map((arr) => {
arr = arr.map((str, idx) => {
if(str.length === length[idx]) {
return str;
} else {
if(justification === "left") {
return str + " ".repeat(length[idx] - str.length);
} else if(justification === "right") {
return " ".repeat(length[idx] - str.length) + str;
} else if(justification === "center") {
return " ".repeat(Math.floor((length[idx] - str.length)/2)) + str + " ".repeat(Math.ceil((length[idx] - str.length)/2));
}
}
});
return arr;
});
result = result.reduce((outer, array) => {
outer += array.reduce((inner, curr) => {
inner += curr + ' ';
return inner;
}, '');
return outer + '\n';
}, '')
return result;
}
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(formatText(testText, 'left'));
Your browser information:
User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0.0.0 Safari/537.36
Challenge Information:
Rosetta Code Challenges - Align columns