From a0bb57c5e857519e5fe8434237d94b9cb054fbc8 Mon Sep 17 00:00:00 2001 From: MA Beaudet Date: Fri, 5 Nov 2021 15:37:28 +0100 Subject: [PATCH] feat: eval_from_str split in two functions `eval_from_str` was doing too much. Now `parse_cards` parses the cards and `eval_hand` wraps over `eval_5hand` and `eval_7hand`. Both functions are available through wasm_bindgen --- src/lib.rs | 43 ++++++++++++++++++++++++++++++------------- 1 file changed, 30 insertions(+), 13 deletions(-) diff --git a/src/lib.rs b/src/lib.rs index 83256ac..7792357 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -137,21 +137,38 @@ fn find_fast(mut u: u32) -> u16 { u16::try_from(a).unwrap() ^ HASH_ADJUST[b as usize] } -/// Wrapper over both five-card and seven-card hand evaluator from string. +// #[wasm_bindgen] +// pub fn eval_from_str(s: &str) -> u16 { +// let cards = s.split(' ').map(|c| card_from_str(c)).collect::>(); +// match cards.len() { +// 7 => eval_7hand(&cards.try_into().unwrap()), +// 5 => eval_5hand(&cards.try_into().unwrap()), +// _ => 9999, +// } +// } + +#[wasm_bindgen] +pub fn parse_cards(s: &str) -> Vec { + s.trim() + .split_whitespace() + .map(|c| parse_card(c).expect("Could not parse card from string")) + .collect::>() +} + +/// Wrapper over both five-card and seven-card hand evaluator from a vector of cards. /// /// The evaluator orders hands from 1 to 7462. /// /// # Example /// /// ``` -/// use poker_eval::{eval_from_str}; +/// use poker_eval::{eval_hand, parse_cards}; /// -/// assert_eq!(eval_from_str("4s 4d 4h 4c 5d"), 140); -/// assert_eq!(eval_from_str("Ts 9s 8s 7s 6s 7h 6d"), 5); +/// assert_eq!(eval_hand(parse_cards("4s 4d 4h 4c 5d")), 140); +/// assert_eq!(eval_hand(parse_cards("Ts 9s 8s 7s 6s 7h 6d")), 5); /// ``` #[wasm_bindgen] -pub fn eval_from_str(s: &str) -> u16 { - let cards = s.split(' ').map(|c| card_from_str(c)).collect::>(); +pub fn eval_hand(cards: Vec) -> u16 { match cards.len() { 7 => eval_7hand(&cards.try_into().unwrap()), 5 => eval_5hand(&cards.try_into().unwrap()), @@ -199,9 +216,9 @@ pub fn eval_7hand(hand: &[u32; 7]) -> u16 { /// # Example /// /// ``` -/// use poker_eval::{eval_from_str, hand_rank, constants::FLUSH}; +/// use poker_eval::{eval_hand, hand_rank, parse_cards, constants::FLUSH}; /// -/// let eval = eval_from_str("Js 9s 7s 3s 2s"); +/// let eval = eval_hand(parse_cards("Js 9s 7s 3s 2s")); /// assert_eq!(eval, 1433); /// assert_eq!(hand_rank(eval), FLUSH); /// ``` @@ -342,11 +359,11 @@ mod tests { ); } #[test] - fn eval_hand() { - assert_eq!(eval_from_str("Js 9s 7s 3s 2s"), 1433); - assert_eq!(eval_from_str("6s 6d 6h Qs Qd"), 265); - assert_eq!(eval_from_str("4s 4d 4h 4c 5d"), 140); - assert_eq!(eval_from_str("Ts 9s 8s 7s 6s 7h 6d"), 5); + fn eval_cards() { + assert_eq!(eval_hand(parse_cards("Js 9s 7s 3s 2s")), 1433); + assert_eq!(eval_hand(parse_cards("6s 6d 6h Qs Qd")), 265); + assert_eq!(eval_hand(parse_cards("4s 4d 4h 4c 5d")), 140); + assert_eq!(eval_hand(parse_cards("Ts 9s 8s 7s 6s 7h 6d")), 5); } #[test] -- 2.20.1