redux_rs/reducer.rs
1/// # Reducer trait
2/// A reducer is responsible to calculate the next state based on the current state and an action.
3/// You can do this by implementing the `Reducer` or a function with the signature `Fn(State, Action) -> State`
4///
5/// ## Trait example
6/// ```
7/// use redux_rs::Reducer;
8///
9/// enum Action {
10/// Increment,
11/// Decrement,
12/// }
13///
14/// impl Reducer<u8, Action> for u8 {
15/// fn reduce(&self, state: u8, action: Action) -> u8 {
16/// match action {
17/// Action::Increment => state + 1,
18/// Action::Decrement => state - 1,
19/// }
20/// }
21/// }
22/// ```
23///
24/// ## Fn example
25/// ```
26/// use redux_rs::Reducer;
27///
28/// enum Action {
29/// Increment,
30/// Decrement,
31/// }
32///
33/// fn reduce(state: u8, action: Action) -> u8 {
34/// match action {
35/// Action::Increment => state + 1,
36/// Action::Decrement => state - 1,
37/// }
38/// }
39/// ```
40pub trait Reducer<State, Action> {
41 /// Method gets called every time a user dispatches an action to the store.
42 /// This method takes the previous state and the action and is supposed to calculate the new state.
43 fn reduce(&self, state: State, action: Action) -> State;
44}
45
46impl<F, State, Action> Reducer<State, Action> for F
47where
48 F: Fn(State, Action) -> State,
49{
50 fn reduce(&self, state: State, action: Action) -> State {
51 self(state, action)
52 }
53}