From 23c0b242e9841fc0def9cf28c1eb102dd1264686 Mon Sep 17 00:00:00 2001 From: runebaas Date: Sun, 27 Oct 2019 22:34:48 +0100 Subject: [PATCH] Add some functions --- src/main.rs | 35 +++++++++++++++++++++-------------- 1 file changed, 21 insertions(+), 14 deletions(-) diff --git a/src/main.rs b/src/main.rs index 48416c1..d71998b 100644 --- a/src/main.rs +++ b/src/main.rs @@ -23,27 +23,34 @@ fn main() { .value_name("length")); let matches = app.get_matches(); - // get fortunes + // input variables let filename = matches.value_of("file").unwrap().to_owned(); - let fortune_file = fs::read_to_string(filename).expect("Cannot read fortune file"); - let fortunes: Vec<&str> = fortune_file.split('%').collect(); + let max_length = matches.value_of("length").unwrap().parse::().expect("Length is not a valid number"); + + // get fortunes + let fortunes = get_fortunes(filename); // filter by max length - let max_length = matches - .value_of("length") - .unwrap() - .parse::() - .expect("Length is not a valid number"); let filtered = fortunes .into_iter() .filter(|x| x.replace(" ", "").len() < max_length) - .collect::>(); + .collect::>(); // get a random one - let total_fortunes = filtered.len(); - let random_fortune = rand::thread_rng().gen_range(0, total_fortunes); - - // print the fortune - let the_fortune = filtered.get(random_fortune).unwrap().trim(); + let the_fortune = get_random_fortune(filtered); println!("{}", the_fortune); } + +fn get_fortunes(filename: String) -> Vec { + let fortune_file = fs::read_to_string(filename).expect("Cannot read fortune file"); + let fortunes: Vec = fortune_file.split('%').map(ToOwned::to_owned).collect(); + + return fortunes; +} + +fn get_random_fortune(fortunes: Vec) -> String { + let total_fortunes = fortunes.len(); + let random_fortune = rand::thread_rng().gen_range(0, total_fortunes); + + return fortunes.get(random_fortune).unwrap().trim().to_owned(); +}