Add some functions

This commit is contained in:
runebaas 2019-10-27 22:34:48 +01:00
parent 1ff4df9050
commit 23c0b242e9
No known key found for this signature in database
GPG key ID: 2677AF508D0300D6

View file

@ -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::<usize>().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::<usize>()
.expect("Length is not a valid number");
let filtered = fortunes
.into_iter()
.filter(|x| x.replace(" ", "").len() < max_length)
.collect::<Vec<&str>>();
.collect::<Vec<String>>();
// 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<String> {
let fortune_file = fs::read_to_string(filename).expect("Cannot read fortune file");
let fortunes: Vec<String> = fortune_file.split('%').map(ToOwned::to_owned).collect();
return fortunes;
}
fn get_random_fortune(fortunes: Vec<String>) -> 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();
}