Add some functions
This commit is contained in:
parent
1ff4df9050
commit
23c0b242e9
1 changed files with 21 additions and 14 deletions
35
src/main.rs
35
src/main.rs
|
@ -23,27 +23,34 @@ fn main() {
|
||||||
.value_name("length"));
|
.value_name("length"));
|
||||||
let matches = app.get_matches();
|
let matches = app.get_matches();
|
||||||
|
|
||||||
// get fortunes
|
// input variables
|
||||||
let filename = matches.value_of("file").unwrap().to_owned();
|
let filename = matches.value_of("file").unwrap().to_owned();
|
||||||
let fortune_file = fs::read_to_string(filename).expect("Cannot read fortune file");
|
let max_length = matches.value_of("length").unwrap().parse::<usize>().expect("Length is not a valid number");
|
||||||
let fortunes: Vec<&str> = fortune_file.split('%').collect();
|
|
||||||
|
// get fortunes
|
||||||
|
let fortunes = get_fortunes(filename);
|
||||||
|
|
||||||
// filter by max length
|
// filter by max length
|
||||||
let max_length = matches
|
|
||||||
.value_of("length")
|
|
||||||
.unwrap()
|
|
||||||
.parse::<usize>()
|
|
||||||
.expect("Length is not a valid number");
|
|
||||||
let filtered = fortunes
|
let filtered = fortunes
|
||||||
.into_iter()
|
.into_iter()
|
||||||
.filter(|x| x.replace(" ", "").len() < max_length)
|
.filter(|x| x.replace(" ", "").len() < max_length)
|
||||||
.collect::<Vec<&str>>();
|
.collect::<Vec<String>>();
|
||||||
|
|
||||||
// get a random one
|
// get a random one
|
||||||
let total_fortunes = filtered.len();
|
let the_fortune = get_random_fortune(filtered);
|
||||||
let random_fortune = rand::thread_rng().gen_range(0, total_fortunes);
|
|
||||||
|
|
||||||
// print the fortune
|
|
||||||
let the_fortune = filtered.get(random_fortune).unwrap().trim();
|
|
||||||
println!("{}", the_fortune);
|
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();
|
||||||
|
}
|
||||||
|
|
Loading…
Reference in a new issue