RosettaCodeData/Task/Align-columns/Shiny/align-columns.shiny

40 lines
1.2 KiB
Plaintext

text: '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.'
align: action text; position;
# split text into 2D array of lines and words
lines : { for text.split ~\$?\r?\n~ { for a.split '$' a end } end }
# calculate max required width for each column
widths: { for lines for a here[b]: a.length.max here[b]? ends }
spaces: action out ("%%%ds" in).format '' end
# formatting functions
left: action word; width;
pad: width-word.length
print "%s%s " word spaces pad
end
right: action word; width;
pad: width-word.length
print "%s%s " spaces pad word
end
center: action word; width;
pad: (width-word.length)/2
print "%s%s%s " spaces pad.floor word spaces pad.ceil
end
if position.match ~^(left|center|right)$~ for lines
for a local[position] a widths[b] end say ''
ends say ''
end
align text 'left'
align text 'center'
align text 'right'