diff options
| author | Mistivia <i@mistivia.com> | 2025-04-28 14:47:16 +0800 |
|---|---|---|
| committer | Mistivia <i@mistivia.com> | 2025-04-28 14:47:16 +0800 |
| commit | 967c820df9d2f2b3bd2dacbc0ae2ed62c985d26f (patch) | |
| tree | 8681edd5d0c33a71d059a33d7b37224d97603c29 | |
| parent | be451eb174f33b93afa2d1685129033c55fc632f (diff) | |
human readable duration format
| -rw-r--r-- | 4-kyu/human-readable-duration-format.hs | 26 |
1 files changed, 26 insertions, 0 deletions
diff --git a/4-kyu/human-readable-duration-format.hs b/4-kyu/human-readable-duration-format.hs new file mode 100644 index 0000000..d506d2a --- /dev/null +++ b/4-kyu/human-readable-duration-format.hs @@ -0,0 +1,26 @@ +-- https://www.codewars.com/kata/52742f58faf5485cae000b9a +module FormatDuration where + +import Data.List + +units = ["second", "minute", "hour", "day", "year"] + +unitsLen :: (Integral i) => [i] +unitsLen = [60, 60, 24, 365] + +seris [] cur ret = reverse (cur:ret) +seris (x:xs) cur ret = seris xs (cur `div` x) ((cur `mod` x):ret) + +zipUnit nums = filter (/="") $ zipWith fn nums units + where + fn 0 unit = "" + fn 1 unit = "1 " ++ unit + fn n unit = (show n) ++ " " ++ unit ++ "s" + +joinUnits :: [String] -> String +joinUnits [x] = x +joinUnits (x:xs) = (intercalate ", " $ reverse xs) ++ " and " ++ x + +formatDuration :: (Integral i, Show i) => i -> String +formatDuration n = if toInteger n == 0 then "now" + else joinUnits $ zipUnit $ seris unitsLen n [] |
