Skip to content

Commit

Permalink
day8 challenge
Browse files Browse the repository at this point in the history
  • Loading branch information
m4salah committed Dec 8, 2023
1 parent 48f07f5 commit 77608db
Show file tree
Hide file tree
Showing 2 changed files with 87 additions and 0 deletions.
85 changes: 85 additions & 0 deletions src/handlers/day8.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
use axum::{extract::Path, http::StatusCode, response::IntoResponse, routing::get};
use serde::Deserialize;

#[derive(Deserialize, Debug, Clone)]
struct PokeWeight {
weight: u32,
}

impl PokeWeight {
fn extract_weight(&self) -> f64 {
self.weight as f64 / 10.0
}
}

async fn poke_weight(Path(pokedex): Path<u32>) -> impl IntoResponse {
let poke_weight = reqwest::get(format!("https://pokeapi.co/api/v/pokemon/{pokedex}"))
.await
.unwrap()
.json::<PokeWeight>()
.await
.unwrap();

format!("{}", poke_weight.extract_weight())
}

async fn poke_drop(Path(pokedex): Path<u32>) -> impl IntoResponse {
let poke_weight = reqwest::get(format!("https://pokeapi.co/api/v2/pokemon/{pokedex}"))
.await
.unwrap()
.json::<PokeWeight>()
.await
.unwrap();

println!(
"{}",
poke_weight.extract_weight() * (9.825f64 * 10.0 * 2.0).sqrt()
);
format!(
"{}",
poke_weight.extract_weight() * (9.825f64 * 10.0 * 2.0).sqrt()
)
}

pub fn router() -> axum::Router {
axum::Router::new()
.route("/8", get(|| async { StatusCode::OK }))
.route("/8/weight/:pokedex", get(poke_weight))
.route("/8/drop/:pokedex", get(poke_drop))
}

#[cfg(test)]
mod tests {
use super::*;
use axum::http::StatusCode;
use axum_test_helper::TestClient;

#[tokio::test]
async fn day8_health() {
let app = router();

let client = TestClient::new(app);
let res = client.get("/8").send().await;
assert_eq!(res.status(), StatusCode::OK);
}

#[tokio::test]
async fn day8_poke_weight() {
let app = router();

let client = TestClient::new(app);
let res = client.get("/8/weight/25").send().await;
assert_eq!(res.status(), StatusCode::OK);
assert_eq!(res.text().await, "6");
}

#[tokio::test]
async fn day8_poke_drop() {
let app = router();

let client = TestClient::new(app);
let res = client.get("/8/drop/25").send().await;
assert_eq!(res.status(), StatusCode::OK);
assert!(res.text().await.parse::<f64>().unwrap() - 84.10707461325713 <= 0.001);
}
}
2 changes: 2 additions & 0 deletions src/handlers/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ mod day1;
mod day4;
mod day6;
mod day7;
mod day8;

pub fn router() -> axum::Router {
axum::Router::new()
Expand All @@ -12,4 +13,5 @@ pub fn router() -> axum::Router {
.nest("/", day4::router())
.nest("/", day6::router())
.nest("/", day7::router())
.nest("/", day8::router())
}

0 comments on commit 77608db

Please sign in to comment.