Last active
August 4, 2020 21:06
-
-
Save chemacortes/67cbbc22595a9ec3993298975824bf15 to your computer and use it in GitHub Desktop.
Padding in elm
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module Fmt exposing (..) | |
import String | |
type FmtPadding | |
= Default | |
| Left Int Char | |
| Right Int Char | |
| Center Int Char | |
| FloatingPoint Int Int | |
type FmtSign | |
= None | |
| Always | |
| OnlyNegative | |
| Space | |
| OnRight | |
type alias Fmt a = | |
{ toString : a -> String | |
, padding : FmtPadding | |
, sign : FmtSign | |
} | |
fmtString : Fmt String | |
fmtString = | |
{ toString = identity | |
, padding = Default | |
, sign = None | |
} | |
fmtInt : Fmt Int | |
fmtInt = | |
{ toString = String.fromInt | |
, padding = Left 12 ' ' | |
, sign = Space | |
} | |
fmtFloat : Fmt Float | |
fmtFloat = | |
{ toString = String.fromFloat | |
, padding = FloatingPoint 16 3 | |
, sign = Always | |
} | |
padLeft : Int -> Fmt a -> Fmt a | |
padLeft n fmt = | |
{ fmt | padding = Left n ' ' } | |
padRight : Int -> Fmt a -> Fmt a | |
padRight n fmt = | |
{ fmt | padding = Right n ' ' } | |
padCenter : Int -> Fmt a -> Fmt a | |
padCenter n fmt = | |
{ fmt | padding = Center n ' ' } | |
padFloatingPoint : Int -> Int -> Fmt a -> Fmt a | |
padFloatingPoint n d fmt = | |
{ fmt | padding = FloatingPoint n d } | |
withPadChar : Char -> Fmt a -> Fmt a | |
withPadChar c fmt = | |
let | |
padding = | |
case fmt.padding of | |
Left n _ -> | |
Left n c | |
Right n _ -> | |
Right n c | |
Center n _ -> | |
Center n c | |
_ -> | |
fmt.padding | |
in | |
{ fmt | padding = padding } | |
toString : a -> Fmt a -> String | |
toString x fmt = | |
case fmt.padding of | |
Default -> | |
fmt.toString x | |
Left n c -> | |
fmt.toString x |> String.padLeft n c | |
Right n c -> | |
fmt.toString x |> String.padRight n c | |
Center n c -> | |
fmt.toString x |> String.pad n c | |
FloatingPoint n d -> | |
fmt.toString x |> toStringFP n d | |
toStringFP : Int -> Int -> String -> String | |
toStringFP n d s = | |
let | |
lst = | |
String.split "." s | |
in | |
case lst of | |
left :: right :: [] -> | |
(left ++ "." ++ String.padRight d '0' right) |> String.padLeft n ' ' | |
left :: [] -> | |
(left ++ "." ++ String.padRight d '0' "") |> String.padLeft n ' ' | |
_ -> | |
s | |
sample : String | |
sample = | |
fmtFloat |> toString 1.2 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment