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.

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read more →

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more