From b78b3a2c8bd620dd61a9e1fec94eb9e542319cc1 Mon Sep 17 00:00:00 2001 From: "Mohamed A. Salah" Date: Wed, 6 Dec 2023 20:23:17 +0200 Subject: [PATCH] elf on a shelf challenge --- src/main.rs | 62 +++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 62 insertions(+) diff --git a/src/main.rs b/src/main.rs index 143ff10..ce81285 100644 --- a/src/main.rs +++ b/src/main.rs @@ -97,6 +97,25 @@ async fn contest(Json(reindeers): Json>) -> impl IntoRespon } } +#[derive(Debug, Serialize, Deserialize, Default, PartialEq, Eq)] +struct ElfOnShelfResult { + elf: u32, + #[serde(alias = "elf on a shelf")] + elf_on_shelf: u32, + #[serde(alias = "shelf with no elf on it")] + shelf_with_no_elf: u32, +} +async fn elf_on_shelf(elf_text: String) -> impl IntoResponse { + let shelf = elf_text.matches("shelf").count() as u32; + let elf_on_shelf = elf_text.matches("elf on a shelf").count() as u32; + let elf = elf_text.matches("elf").count() as u32; + Json(ElfOnShelfResult { + elf, + elf_on_shelf, + shelf_with_no_elf: shelf - elf_on_shelf, + }) +} + #[allow(dead_code)] fn app() -> Router { Router::new() @@ -105,6 +124,7 @@ fn app() -> Router { .route("/1/*ids", get(packet_ids)) .route("/4/strength", post(sum_strength)) .route("/4/contest", post(contest)) + .route("/6", post(elf_on_shelf)) } #[shuttle_runtime::main] @@ -267,4 +287,46 @@ mod tests { .await; assert_eq!(res.status(), StatusCode::BAD_REQUEST); } + + #[tokio::test] + async fn elf() { + let app = app(); + + let client = TestClient::new(app); + let res = client + .post("/6") + .body( + "The mischievous elf peeked out from behind the toy workshop, + and another elf joined in the festive dance. + Look, there is also an elf on that shelf!", + ) + .header("Content-Type", "text/plain") + .send() + .await; + assert_eq!(res.status(), StatusCode::OK); + let expected = ElfOnShelfResult { + elf: 4, + ..Default::default() + }; + assert_eq!(res.json::().await.elf, expected.elf); + } + #[tokio::test] + async fn elf_on_shelf() { + let app = app(); + + let client = TestClient::new(app); + let res = client + .post("/6") + .body("there is an elf on a shelf on an elf. there is also another shelf in Belfast.") + .header("Content-Type", "text/plain") + .send() + .await; + assert_eq!(res.status(), StatusCode::OK); + let expected = ElfOnShelfResult { + elf: 5, + shelf_with_no_elf: 1, + elf_on_shelf: 1, + }; + assert_eq!(res.json::().await, expected); + } }