RosettaCodeData/Task/Align-columns/Sidef/align-columns-2.sidef

71 lines
2.5 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.
'.
printSep :=
[:colLengths |
Stdout nextPut:$+.
colLengths do:[:len | Stdout next:len put:$-; nextPut:$+ ].
Stdout cr.
].
printRows :=
[:text :box :justifyEach |
lines := StringCollection fromString:text.
rowSet := lines collect:[:line | line splitBy:$$ ].
maxNumCols := (rowSet collect:[:row | row size]) max.
maxLengths := rowSet
inject:(Array new:maxNumCols withAll:0)
into:[:maxesSoFar :row|
maxesSoFar
with:(row paddedTo:maxNumCols with:'')
collect:[:maxLen :col | maxLen max: col size]].
rowSet do:[:row |
|first|
box ifTrue:[ printSep value:maxLengths ].
first := true.
(box ifTrue:[row paddedTo:maxLengths size with:''] ifFalse:[row])
with: (box ifTrue:[maxLengths] ifFalse:[maxLengths to:row size])
do:[:col :len |
first ifTrue:[ box ifTrue:[Stdout nextPutAll:'|']. first := false.].
Stdout print:(justifyEach value:col value:len).
Stdout nextPutAll:(box ifTrue:'|' ifFalse:' ')
].
Stdout cr.
].
box ifTrue:[ printSep value:maxLengths ].
].
printRightJustified :=
[:text :box | printRows value:text value:box value:[:col :len | (col leftPaddedTo:len)]].
printLeftJustified :=
[:text :box | printRows value:text value:box value:[:col :len | (col paddedTo:len)]].
printCentered :=
[:text :box | printRows value:text value:box value:[:col :len | col centerPaddedTo:len]].
Stdout printCR:'Left justified:'.
printLeftJustified value:text value:false.
Stdout cr; printCR:'Right justified:'.
printRightJustified value:text value:false.
Stdout cr; printCR:'Centered:'.
printCentered value:text value:false.
Stdout cr; printCR:'Left justified with box:'.
printLeftJustified value:text value:true.
Stdout cr; printCR:'Right justified with box:'.
printRightJustified value:text value:true.
Stdout cr; printCR:'Centered with box:'.
printCentered value:text value:true.