Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

JS側のRegExpを使用する: read_house_number.rs #132

Merged
49 changes: 40 additions & 9 deletions src/parser/read_house_number.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
use regex::Regex;

#[allow(dead_code)]
pub fn read_house_number(input: &str) -> Option<(String, String)> {
let expression = Regex::new(r"(?<house_number>\d+)\D*(?<rest>.*)$").unwrap();
#[cfg(not(target_arch = "wasm32"))]
fn read_house_number_with_regex(input: &str) -> Option<(String, String)> {
let expression = regex::Regex::new(r"(?<house_number>\d+)\D*(?<rest>.*)$").unwrap();
let captures = expression.captures(input)?;
let house_number = if let Some(matched) = captures.name("house_number") {
matched.as_str()
Expand All @@ -17,20 +16,52 @@ pub fn read_house_number(input: &str) -> Option<(String, String)> {
Some((rest.to_string(), format!("{}番", house_number)))
}

#[cfg(test)]
mod read_house_number_tests {
use crate::parser::read_house_number::read_house_number;
#[allow(dead_code)]
#[cfg(target_arch = "wasm32")]
fn read_house_number_with_js_sys_regexp(input: &str) -> Option<(String, String)> {
let expression = js_sys::RegExp::new(r"(?<house_number>\d+)\D*(?<rest>.*)$", "");
let captures = expression.exec(input)?;
let house_number = captures.get(1).as_string()?;
let rest = captures
.get(2)
.as_string()
.unwrap_or_else(|| "".to_string());
Some((rest, format!("{}番", house_number)))
}

#[cfg(all(test, not(target_arch = "wasm32")))]
mod tests {
use crate::parser::read_house_number::read_house_number_with_regex;

#[test]
fn read_house_number_1番() {
let (rest, house_number) = read_house_number("1").unwrap();
let (rest, house_number) = read_house_number_with_regex("1").unwrap();
assert_eq!(house_number, "1番");
assert_eq!(rest, "");
}

#[test]
fn read_house_number_3番2() {
let (rest, house_number) = read_house_number("3-2").unwrap();
let (rest, house_number) = read_house_number_with_regex("3-2").unwrap();
assert_eq!(house_number, "3番");
assert_eq!(rest, "2");
}
}

#[cfg(all(test, target_arch = "wasm32"))]
mod wasm_tests {
use crate::parser::read_house_number::read_house_number_with_js_sys_regexp;
use wasm_bindgen_test::{wasm_bindgen_test, wasm_bindgen_test_configure};

wasm_bindgen_test_configure!(run_in_browser);

#[wasm_bindgen_test]
fn read_house_number_with_js_sys_regexp_success() {
let (rest, house_number) = read_house_number_with_js_sys_regexp("1").unwrap();
assert_eq!(house_number, "1番");
assert_eq!(rest, "");

let (rest, house_number) = read_house_number_with_js_sys_regexp("3-2").unwrap();
assert_eq!(house_number, "3番");
assert_eq!(rest, "2");
}
Expand Down
Loading