From 8b88cbff75ec3ecda69992aca266ed15fb7865fd Mon Sep 17 00:00:00 2001 From: Jonathan Lamothe Date: Mon, 2 Sep 2019 09:54:04 -0400 Subject: [PATCH] implemented centre --- src/Mtlstats/Format.hs | 14 ++++++++++++++ test/FormatSpec.hs | 12 ++++++++++++ 2 files changed, 26 insertions(+) diff --git a/src/Mtlstats/Format.hs b/src/Mtlstats/Format.hs index fe0f6cf..050fe0d 100644 --- a/src/Mtlstats/Format.hs +++ b/src/Mtlstats/Format.hs @@ -23,6 +23,7 @@ module Mtlstats.Format ( padNum , left , right + , centre ) where -- | Pad an 'Int' with leading zeroes to fit a certain character width @@ -58,3 +59,16 @@ right -- ^ The text to align -> String 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 ' ' diff --git a/test/FormatSpec.hs b/test/FormatSpec.hs index 113b4c0..c4d8484 100644 --- a/test/FormatSpec.hs +++ b/test/FormatSpec.hs @@ -30,6 +30,7 @@ spec = describe "Mtlstats.Format" $ do padNumSpec leftSpec rightSpec + centreSpec padNumSpec :: Spec padNumSpec = describe "padNum" $ do @@ -75,3 +76,14 @@ rightSpec = describe "right" $ do context "overflow" $ it "should truncate the text" $ 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"