use super::CollectionProxy;
use crate::proxy::ProxyResult;
use crate::proxy::ScalarValue;
#[derive(Debug, Clone)]
pub struct CollectionOperations {
proxy: CollectionProxy,
}
impl CollectionOperations {
pub fn new(proxy: CollectionProxy) -> Self {
Self { proxy }
}
pub async fn filter<T, F>(&self, source: &T, predicate: F) -> ProxyResult<Vec<ScalarValue>>
where
T: crate::proxy::reflection::Reflectable,
F: Fn(&ScalarValue) -> bool,
{
let values = self.proxy.get_values(source).await?;
Ok(values.into_iter().filter(|v| predicate(v)).collect())
}
pub async fn map<T, F, U>(&self, source: &T, mapper: F) -> ProxyResult<Vec<U>>
where
T: crate::proxy::reflection::Reflectable,
F: Fn(&ScalarValue) -> U,
{
let values = self.proxy.get_values(source).await?;
Ok(values.iter().map(mapper).collect())
}
pub async fn sort<T>(&self, source: &T) -> ProxyResult<Vec<ScalarValue>>
where
T: crate::proxy::reflection::Reflectable,
{
let mut values = self.proxy.get_values(source).await?;
values.sort_by(|a, b| format!("{:?}", a).cmp(&format!("{:?}", b)));
Ok(values)
}
pub async fn distinct<T>(&self, source: &T) -> ProxyResult<Vec<ScalarValue>>
where
T: crate::proxy::reflection::Reflectable,
{
let mut values = self.proxy.get_values(source).await?;
values.sort_by(|a, b| format!("{:?}", a).cmp(&format!("{:?}", b)));
values.dedup_by(|a, b| format!("{:?}", a) == format!("{:?}", b));
Ok(values)
}
}