RosettaCodeData/Task/Align-columns/Jsish/align-columns.jsish

43 lines
1.6 KiB
Plaintext

/* Align columns, in Jsish */
function alignColumns(phrases:array, just:string) {
var x, y, max, diff, left, right, cols=0;
for(x=0; x<phrases.length; x++) {
phrases[x] = phrases[x].split("$");
if (phrases[x].length>cols) cols=phrases[x].length;
}
for (x=0; x<cols; x++) {
max = 0;
for (y=0; y<phrases.length; y++) if (phrases[y][x] && max<phrases[y][x].length) max = phrases[y][x].length;
for (y=0; y<phrases.length; y++) {
if (phrases[y][x]) {
diff = (max-phrases[y][x].length)/2;
left = " ".repeat(Math.floor(diff));
right = " ".repeat(Math.ceil(diff));
if (just == "left") { right += left; left=""; }
if (just == "right") { left += right; right=""; }
phrases[y][x] = left + phrases[y][x] + right;
}
}
}
for (x=0; x<phrases.length; x++) phrases[x] = phrases[x].join(" ");
phrases = phrases.join("\n");
return phrases;
}
if (Interp.conf('unitTest')) {
var phrases = ["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."];
for (var just of ['left', 'center', 'right']) {
var trial = phrases.slice(0);
puts(just);
puts(alignColumns(trial, just), '\n');
}
}