DEV Community

loading...

Discussion on: Daily Challenge #54 - What century is it?

Collapse
citizen428 profile image
Michael Kohl

F#:

module Century

let private parseYear s =
    let n = int s
    if n >= 0 then Ok n
    else Error "Year must be >= 0"

let private suffix c =
    match c % 100 with
    | 11
    | 12
    | 13 -> "th"
    | _ ->
        match c % 10 with
        | 1 -> "st"
        | 2 -> "nd"
        | 3 -> "rd"
        | _ -> "th"

let century (year : string) =
    match parseYear year with
    | Ok year ->
        let c = year / 100 + 1
        sprintf "%d%s" c (suffix c)
    | Error msg -> failwith msg

Failing on inputs < 0 was an arbitrary decision, it's easy to adopt the current code to take care of BC/AD.

Tests:

module CenturyTest

open FsUnit.Xunit
open Xunit
open Century

[<Fact>]
let ``2259``() = century "2259" |> should equal "23rd"

[<Fact>]
let ``1124``() = century "1124" |> should equal "12th"

[<Fact>]
let ``2000``() = century "2000" |> should equal "21st"

[<Fact>]
let ``0``() = century "0" |> should equal "1st"

[<Fact>]
let ``111``() = century "111" |> should equal "2nd"

[<Fact>]
let ``2245``() = century "2245" |> should equal "23rd"

[<Fact>]
let ``invalid year``() = (fun () -> century "-1" |> ignore) |> shouldFail