DEV Community

Cover image for Think/Code
Antonov Mike
Antonov Mike

Posted on

1

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.

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay