rust_lodash/chain/
builder.rs

1//! Chain builder module for constructing complex operation chains.
2
3use crate::chain::{Chain, Operation};
4
5#[cfg(feature = "async")]
6use crate::chain::{AsyncChain, AsyncOperation};
7
8/// Builder for creating complex operation chains.
9pub struct ChainBuilder<T> {
10    data: Vec<T>,
11    operations: Vec<Operation<T>>,
12}
13
14impl<T> ChainBuilder<T> {
15    /// Create a new chain builder.
16    #[must_use]
17    pub fn new(data: Vec<T>) -> Self {
18        Self {
19            data,
20            operations: Vec::new(),
21        }
22    }
23
24    /// Add a map operation to the chain.
25    #[must_use]
26    pub fn map<F>(mut self, mapper: F) -> Self
27    where
28        F: Fn(&T) -> T + Send + Sync + 'static,
29    {
30        self.operations.push(Operation::Map(Box::new(mapper)));
31        self
32    }
33
34    /// Add a filter operation to the chain.
35    #[must_use]
36    pub fn filter<F>(mut self, predicate: F) -> Self
37    where
38        F: Fn(&T) -> bool + Send + Sync + 'static,
39    {
40        self.operations.push(Operation::Filter(Box::new(predicate)));
41        self
42    }
43
44    /// Build the chain.
45    #[must_use]
46    pub fn build(self) -> Chain<T> {
47        Chain {
48            data: self.data,
49            operations: self.operations,
50        }
51    }
52}
53
54/// Builder for creating complex async operation chains.
55#[cfg(feature = "async")]
56pub struct AsyncChainBuilder<T> {
57    data: Vec<T>,
58    operations: Vec<AsyncOperation<T>>,
59}
60
61#[cfg(feature = "async")]
62impl<T> AsyncChainBuilder<T> {
63    /// Create a new async chain builder.
64    pub fn new(data: Vec<T>) -> Self {
65        Self {
66            data,
67            operations: Vec::new(),
68        }
69    }
70
71    /// Add an async map operation to the chain.
72    pub fn map_async<F, Fut>(mut self, mapper: F) -> Self
73    where
74        F: Fn(&T) -> Fut + Send + Sync + 'static,
75        Fut: std::future::Future<Output = T> + Send + Sync + 'static,
76    {
77        self.operations.push(AsyncOperation::MapAsync(Box::new(move |x| {
78            Box::pin(mapper(x))
79        })));
80        self
81    }
82
83    /// Add an async filter operation to the chain.
84    pub fn filter_async<F, Fut>(mut self, predicate: F) -> Self
85    where
86        F: Fn(&T) -> Fut + Send + Sync + 'static,
87        Fut: std::future::Future<Output = bool> + Send + Sync + 'static,
88    {
89        self.operations.push(AsyncOperation::FilterAsync(Box::new(move |x| {
90            Box::pin(predicate(x))
91        })));
92        self
93    }
94
95    /// Build the async chain.
96    pub fn build(self) -> AsyncChain<T> {
97        AsyncChain {
98            data: self.data,
99            operations: self.operations,
100        }
101    }
102}