implemented centre

This commit is contained in:
Jonathan Lamothe 2019-09-02 09:54:04 -04:00
parent 6145dd5c0c
commit 8b88cbff75
2 changed files with 26 additions and 0 deletions

View File

@ -23,6 +23,7 @@ module Mtlstats.Format
( padNum ( padNum
, left , left
, right , right
, centre
) where ) where
-- | Pad an 'Int' with leading zeroes to fit a certain character width -- | Pad an 'Int' with leading zeroes to fit a certain character width
@ -58,3 +59,16 @@ right
-- ^ The text to align -- ^ The text to align
-> String -> String
right n str = reverse $ left n $ reverse str right n str = reverse $ left n $ reverse str
-- | Aligns text to the centre within a field (clipping if necessary)
centre
:: Int
-- ^ The width of the field
-> String
-- ^ The text to align
-> String
centre n str = let
sLen = length str
pLen = (n - sLen) `div` 2
pad = replicate pLen ' '
in take n $ pad ++ str ++ repeat ' '

View File

@ -30,6 +30,7 @@ spec = describe "Mtlstats.Format" $ do
padNumSpec padNumSpec
leftSpec leftSpec
rightSpec rightSpec
centreSpec
padNumSpec :: Spec padNumSpec :: Spec
padNumSpec = describe "padNum" $ do padNumSpec = describe "padNum" $ do
@ -75,3 +76,14 @@ rightSpec = describe "right" $ do
context "overflow" $ context "overflow" $
it "should truncate the text" $ it "should truncate the text" $
right 2 "foo" `shouldBe` "oo" right 2 "foo" `shouldBe` "oo"
centreSpec :: Spec
centreSpec = describe "centre" $ do
context "fit" $
it "should pad the text" $
centre 5 "foo" `shouldBe` " foo "
context "overflow" $
it "should truncate the text" $
centre 2 "foo" `shouldBe` "fo"