Skip to content

Commit 790e147

Browse files
committed
enhace the project using iterators
1 parent efc96e7 commit 790e147

File tree

2 files changed

+28
-33
lines changed

2 files changed

+28
-33
lines changed

projects/minigrep/src/lib.rs

Lines changed: 26 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
use std::{ env, error::Error, fs, vec };
1+
use std::{ env, error::Error, fs };
22

33
pub fn run(config: Config) -> Result<(), Box<dyn Error>> {
44
let contents = fs::read_to_string(&config.filepath)?;
@@ -22,20 +22,24 @@ pub struct Config {
2222
}
2323

2424
impl Config {
25-
pub fn build(mut args: Vec<String>) -> Result<Config, &'static str> {
26-
if args.len() < 3 {
27-
return Err("Not Enough Arguments");
28-
}
29-
let query = args.remove(1);
30-
let filepath = args.remove(1);
31-
32-
let mut ignore_case = env::var("IGNORE_CASE").is_ok();
33-
34-
for arg in args.iter() {
35-
if arg == "-i" {
36-
ignore_case = true;
25+
pub fn build(mut args: impl Iterator<Item = String>) -> Result<Config, &'static str> {
26+
args.next();
27+
28+
let query = match args.next() {
29+
Some(q) => q,
30+
None => {
31+
return Err("Didn't get the query string");
32+
}
33+
};
34+
35+
let filepath = match args.next() {
36+
Some(q) => q,
37+
None => {
38+
return Err("Didn't get the filepath");
3739
}
38-
}
40+
};
41+
42+
let ignore_case = env::var("IGNORE_CASE").is_ok();
3943

4044
Ok(Config {
4145
query,
@@ -46,28 +50,19 @@ impl Config {
4650
}
4751

4852
fn search<'a>(query: &str, contents: &'a str) -> Vec<&'a str> {
49-
let mut results = vec![];
50-
51-
contents.lines().for_each(|line| {
52-
if line.contains(query) {
53-
results.push(line);
54-
}
55-
});
56-
57-
results
53+
contents
54+
.lines()
55+
.filter(|line| line.contains(query))
56+
.collect()
5857
}
5958

6059
fn search_case_insensitive<'a>(query: &str, contents: &'a str) -> Vec<&'a str> {
61-
let mut results = vec![];
6260
let query = query.to_lowercase();
6361

64-
contents.lines().for_each(|line| {
65-
if line.to_lowercase().contains(&query) {
66-
results.push(line);
67-
}
68-
});
69-
70-
results
62+
contents
63+
.lines()
64+
.filter(|line| line.to_lowercase().contains(&query))
65+
.collect()
7166
}
7267

7368
#[cfg(test)]

projects/minigrep/src/main.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,9 +3,9 @@ use std::{ env, process };
33
use minigrep::Config;
44

55
fn main() {
6-
let args: Vec<String> = env::args().collect();
6+
// let args: Vec<String> = env::args().collect();
77

8-
let config: Config = Config::build(args).unwrap_or_else(|err| {
8+
let config: Config = Config::build(env::args()).unwrap_or_else(|err| {
99
eprintln!("Problem parsing arguments: {err}");
1010
process::exit(1);
1111
});

0 commit comments

Comments
 (0)