DEV Community

Cover image for Think/Code
Antonov Mike
Antonov Mike

Posted on

Think/Code

Day three of code refactoring... Trying to start to think this way

My original code:

let mut results: Vec<u32> = engine.search(&input);
let total = results.len();
if total > 10 {
    results.drain(10..);
}
let mut top_ten: Vec<(u32, String)> = vec![];
for index in results {
    top_ten.push((index, catalog[index as usize].1.clone()))
}

let mut answer_vec: Vec<u32> = vec![];
for (i, _) in top_ten.iter() {
    answer_vec.push(*i)
}
Enter fullscreen mode Exit fullscreen mode

After refactoring and explanations:

let answer_vec: Vec<u32> = engine
    .search(&input)
    .into_iter()
    .take(10)
    .collect();
Enter fullscreen mode Exit fullscreen mode

Both do the same:
1) Send "input" to search function
2) Iterate through it's output
3) Take first 10 elements
4) Collect them into a vector
But look different.

It's important to catch an idea before you start to write code. If you can't - write step by step like in the first example then try to figure out what your idea actually is and try to refactor.

Top comments (0)