rust_lodash/chain/
builder.rs1use crate::chain::{Chain, Operation};
4
5#[cfg(feature = "async")]
6use crate::chain::{AsyncChain, AsyncOperation};
7
8pub struct ChainBuilder<T> {
10 data: Vec<T>,
11 operations: Vec<Operation<T>>,
12}
13
14impl<T> ChainBuilder<T> {
15 #[must_use]
17 pub fn new(data: Vec<T>) -> Self {
18 Self {
19 data,
20 operations: Vec::new(),
21 }
22 }
23
24 #[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 #[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 #[must_use]
46 pub fn build(self) -> Chain<T> {
47 Chain {
48 data: self.data,
49 operations: self.operations,
50 }
51 }
52}
53
54#[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 pub fn new(data: Vec<T>) -> Self {
65 Self {
66 data,
67 operations: Vec::new(),
68 }
69 }
70
71 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 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 pub fn build(self) -> AsyncChain<T> {
97 AsyncChain {
98 data: self.data,
99 operations: self.operations,
100 }
101 }
102}