rust_lodash/chain/
executor.rs1use crate::chain::{Chain, Operation};
4
5#[cfg(feature = "async")]
6use crate::chain::{AsyncChain, AsyncOperation};
7
8pub struct ChainExecutor<T> {
10 chain: Chain<T>,
11}
12
13impl<T> ChainExecutor<T> {
14 #[must_use]
16 pub fn new(chain: Chain<T>) -> Self {
17 Self { chain }
18 }
19
20 #[must_use]
22 pub fn execute(self) -> Vec<T> {
23 let mut result = self.chain.data;
24
25 for operation in self.chain.operations {
26 match operation {
27 Operation::Map(mapper) => {
28 result = result.into_iter().map(|x| mapper(&x)).collect();
29 }
30 Operation::Filter(predicate) => {
31 result.retain(|x| predicate(x));
32 }
33 Operation::Take(n) => {
34 result = result.into_iter().take(n).collect();
35 }
36 Operation::Skip(n) => {
37 result = result.into_iter().skip(n).collect();
38 }
39 Operation::Reverse => {
40 result.reverse();
41 }
42 }
43 }
44
45 result
46 }
47}
48
49#[cfg(feature = "async")]
51pub struct AsyncChainExecutor<T> {
52 chain: AsyncChain<T>,
53}
54
55#[cfg(feature = "async")]
56impl<T> AsyncChainExecutor<T> {
57 pub fn new(chain: AsyncChain<T>) -> Self {
59 Self { chain }
60 }
61
62 pub async fn execute(self) -> Vec<T> {
64 let mut result = self.chain.data;
65
66 for operation in self.chain.operations {
67 match operation {
68 AsyncOperation::MapAsync(mapper) => {
69 let mut new_result = Vec::new();
70 for item in result {
71 let mapped = mapper(&item).await;
72 new_result.push(mapped);
73 }
74 result = new_result;
75 }
76 AsyncOperation::FilterAsync(predicate) => {
77 let mut new_result = Vec::new();
78 for item in result {
79 if predicate(&item).await {
80 new_result.push(item);
81 }
82 }
83 result = new_result;
84 }
85 AsyncOperation::Take(n) => {
86 result = result.into_iter().take(n).collect();
87 }
88 AsyncOperation::Skip(n) => {
89 result = result.into_iter().skip(n).collect();
90 }
91 AsyncOperation::Reverse => {
92 result.reverse();
93 }
94 }
95 }
96
97 result
98 }
99}