refactored code in minigrep to properly use iterators.

This commit is contained in:
gabe 2022-08-03 16:21:17 -05:00
parent 6d5c9a730c
commit eb0612b93b
2 changed files with 27 additions and 30 deletions

View file

@ -1,5 +1,5 @@
use std::error::Error;
use std::env;
use std::error::Error;
use std::fs;
pub fn run(config: Config) -> Result<(), Box<dyn Error>> {
@ -22,40 +22,39 @@ pub struct Config {
}
impl Config {
pub fn new(args: &[String]) -> Result<Config, &'static str> {
if args.len() < 3 {
return Err("Not enough arguments");
}
let query = args[1].clone();
let filename = args[2].clone();
pub fn new(mut args: impl Iterator<Item = String>) -> Result<Config, &'static str> {
args.next();
let query = match args.next() {
Some(arg) => arg,
None => return Err("Didn't get a query string."),
};
let filename = match args.next() {
Some(arg) => arg,
None => return Err("Didn't get a file name."),
};
let ignore_case = env::var("IGNORE_CASE").is_ok();
Ok(Config { query, filename, ignore_case })
Ok(Config {
query,
filename,
ignore_case,
})
}
}
pub 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()
}
pub 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)]

View file

@ -4,9 +4,7 @@ use std::process;
use minigrep::Config;
fn main() {
let args: Vec<String> = env::args().collect();
let config = Config::new(&args).unwrap_or_else(|err| {
let config = Config::new(env::args()).unwrap_or_else(|err| {
eprintln!("Problem parsing arguments: {}", err);
process::exit(1);
});