Search code examples
nearprotocol

Paginate the UnorderedSet in near_sdk_rust


I want to paginate the UnorderedSet, can it be done, what collections I have to use for it?

Here is my code:

user_products_map: TreeMap<u128, UnorderedSet<u128>>

pub fn get_products_of_user_id(&self, user_id: u128) -> Vec<u128> {
        let products_set_option = self.user_products_map.get(&user_id);
        match products_set_option {
            Some(products_set) => products_set.to_vec(),
            None => {
                panic!("No products for user");
            }
        }
    }

I want to paginate like:

pub fn get_products_of_user_id(&self, start:u128, end:u128, user_id: u128) -> Vec<u128> {
            let products_set_option = self.user_products_map.get(&user_id);
            match products_set_option {
                Some(products_set) => products_set[start, end].to_vec(),
                None => {
                    panic!("No products for user");
                }
            }
        }

Solution

  • UnorderedSet has iter() method, so you can use standard Rust Iterator methods like skip and take

    products_set.iter().skip(start).take(end).collect()