1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
//! Reducers process issues' records to present a digestable view
//!

/// Generic reducer trait
pub trait Reducer: Sized {
    /// State type
    type State;
    /// Item type
    type Item;

    /// Takes current state, item and returns new state
    fn reduce(&mut self, state: Self::State, item: &Self::Item) -> Self::State;
    /// Chains two reducers together sequentially
    fn chain<R: Reducer<State=Self::State, Item=Self::Item>>(self, other: R) -> ChainedReducer<Self, R> {
       ChainedReducer::new(self, other)
    }
}

#[cfg(feature = "duktape-reducers")]
pub mod duktape;

/// Chained reducer (consists of two reducers)
///
/// Will apply first and then second reducer to a given state
/// when used as a reducer itself
pub struct ChainedReducer<R1: Reducer, R2: Reducer>(R1, R2);

impl<R1: Reducer, R2: Reducer> ChainedReducer<R1, R2> {
    /// Returns a new chain reducer
    pub fn new(r1: R1, r2: R2) -> Self {
        ChainedReducer(r1, r2)
    }
}


impl<T, I, R1: Reducer<State=T, Item=I>, R2: Reducer<State=T, Item=I>> Reducer for ChainedReducer<R1, R2> {
    type State = R1::State;
    type Item = R1::Item;

    fn reduce(&mut self, state: Self::State, item: &Self::Item) -> Self::State {
        self.1.reduce(self.0.reduce(state, item), item)
    }
}

#[cfg(test)]
mod tests {

    use super::Reducer;

    struct R<T>(T);

    impl<T: Clone> Reducer for R<T> {
        type State = T;
        type Item = T;

        fn reduce(&mut self, _state: Self::State, _item: &Self::Item) -> Self::State {
            self.0.clone()
        }
    }

    #[test]
    fn chained_reducer() {
        assert_eq!(R(1).chain(R(2)).reduce(0, &0), 2);
    }

}