From b71e253b697bae079a0cf2526209334f4b81f9a5 Mon Sep 17 00:00:00 2001 From: Adam Carpenter <53hornet@gmail.com> Date: Fri, 1 Mar 2019 14:01:17 -0500 Subject: Added functional and implemented iterators in minigrep. --- minigrep/src/lib.rs | 54 ++++++++++++++++++----------------------------------- 1 file changed, 18 insertions(+), 36 deletions(-) (limited to 'minigrep/src/lib.rs') diff --git a/minigrep/src/lib.rs b/minigrep/src/lib.rs index bf7118f..bb8b4d7 100644 --- a/minigrep/src/lib.rs +++ b/minigrep/src/lib.rs @@ -10,26 +10,20 @@ pub struct Config { impl Config { - pub fn new(args: &[String]) -> Result { + pub fn new(mut args: std::env::Args) -> Result { + args.next(); - if args.len() < 3 { - return Err("Not enough arguments."); - } + let query = match args.next() { + Some(arg) => arg, + None => return Err("Didn't get a query string"), + }; - let query = args[1].clone(); - let filename = args[2].clone(); - let mut case_sensitive = env::var("CASE_INSENSITIVE").is_err(); - - // override environment variable if cli arg is present - if args.len() > 3 { - if args[3] == "-s" { - case_sensitive = true; - } - else if args[3] == "-i" { - case_sensitive = false; - } - } + let filename = match args.next() { + Some(arg) => arg, + None => return Err("Didn't get a filename"), + }; + let case_sensitive = env::var("CASE_INSENSITIVE").is_err(); Ok(Config { query, filename, case_sensitive }) } @@ -54,28 +48,16 @@ pub fn run(config: Config) -> Result<(), Box> { } fn search<'a>(query: &str, contents: &'a str) -> Vec<&'a str> { - let mut results = Vec::new(); - - for line in contents.lines() { - if line.contains(query) { - results.push(line); - } - } - - results + contents.lines() + .filter(|line| line.contains(query)) + .collect() } fn search_case_insensitive<'a>(query: &str, contents: &'a str) -> Vec<&'a str> { - let query = query.to_lowercase(); - let mut results = Vec::new(); - - for line in contents.lines() { - if line.to_lowercase().contains(&query) { - results.push(line); - } - } - - results + contents.lines() + .filter(|line| line.to_lowercase() + .contains(&query.to_lowercase())) + .collect() } #[cfg(test)] -- cgit v1.2.3