DEV Community

Cover image for Misleading comments
Antonov Mike
Antonov Mike

Posted on

Misleading comments

I was asked to write a pagination algorithm for two vectors. The first half of the page should be formed from one vector, the second – from another. I thought maybe I should use something like all_pages to store all the pages. But I was told that this approach was wrong and asked to start from scratch. And then I was told that I had to remove half_page_2, which helped form the page if it had an odd number of elements. These comments have me stumped. And the solution I was offered (incomplete) turned out to be very cumbersome. I don't see the point in finishing the suggested code.
I took a break for a couple of weeks and went back to my original idea a few days ago. I created the all_pages vector and began to add pages formed from two vectors there. And then just “flipping through” the vector to the desired page. And voila! As a result, my code is 60% shorter, easier to read, and does exactly what it's supposed to do.
Sometimes the conditions of a task or someone's comments can lead you to a dead end.
In general, it is always important to check yourself for misconceptions. It does not matter who you are in this situation – the author of the task or the one who is trying to solve it.
The situation is odd.

fn main() {
    let vec_1 = vec![
        "_A", "_B", "_C", "_D", "_E", "_F", "_G", "_H", "_J", "_K", "_L", "_M", "_N", "_P", "_Q",
        "_R", "_S", "_T", "_V", "_W", "_X", "_Y", "_Z",
    ];
    let vec_2 = vec![
        "a ", "b ", "c ", "d ", "e ", "f ", "g ", "h ", "j ", "k ", "l ", "m ", "n ", "p ", "q ",
    ];
    let page_size = 7;
    let page_number = 4;
    println!("{:?}", page_builder(page_size, page_number, vec_1, vec_2));
}

fn page_builder(
    page_size: usize,
    page_number: usize,
    vec_1: Vec<&str>,
    vec_2: Vec<&str>,
) -> Vec<String> {
    let half_page_1 = page_size / 2;
    let half_page_2 = page_size - half_page_1;
    let mut all_pages: Vec<String> = vec![];

    let limit = if vec_1.len() > vec_2.len() {
        vec_1.len()
    } else {
        vec_2.len()
    };

    for i in 0..limit {
        let mut halfvec_1: Vec<String> = vec_1
            .clone()
            .into_iter()
            .skip(i * half_page_1)
            .take(half_page_1)
            .map(Into::into)
            .collect();
        all_pages.append(&mut halfvec_1);

        let mut halfvec_2: Vec<String> = vec_2
            .clone()
            .into_iter()
            .skip(i * half_page_2)
            .take(half_page_2)
            .map(Into::into)
            .collect();
        all_pages.append(&mut halfvec_2)
    }

    let result = all_pages
        .into_iter()
        .skip(page_number * page_size)
        .take(page_size)
        .map(Into::into)
        .collect();
    result
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)