Skip to content

Instantly share code, notes, and snippets.

@mralex
Created February 17, 2016 07:31
Show Gist options
  • Save mralex/74c72afce2a862c4a3c1 to your computer and use it in GitHub Desktop.
Save mralex/74c72afce2a862c4a3c1 to your computer and use it in GitHub Desktop.
Rust Redux counter doodle
#![allow(dead_code)]
// Basic counter
// Most simple initial implementation of Redux
enum ActionTypes {
Increment,
Decrement,
Default,
}
struct Action {
kind: ActionTypes
}
fn reducer(state: i32, action: Action) -> i32 {
let state = match action.kind {
ActionTypes::Increment => state + 1,
ActionTypes::Decrement => state - 1,
_ => state,
};
state
}
struct Store {
state: i32,
reducer: fn(i32, Action) -> i32,
}
impl Store {
fn create_store(reducer: fn(i32, Action) -> i32, initial_state: i32) -> Store {
Store {
state: initial_state,
reducer: reducer,
}
}
fn dispatch(&mut self, action: Action) {
self.state = (self.reducer)(self.state, action);
}
fn get_state(&self) -> i32 {
self.state
}
}
struct ActionCreator;
impl ActionCreator {
fn increment() -> Action {
Action { kind: ActionTypes::Increment }
}
fn decrement() -> Action {
Action { kind: ActionTypes::Decrement }
}
}
fn main() {
let mut store = Store::create_store(reducer, 0);
let state = store.get_state();
println!("state: {}", state);
assert_eq!(state, 0);
store.dispatch(ActionCreator::increment());
let state = store.get_state();
println!("state: {}", state);
assert_eq!(state, 1);
store.dispatch(ActionCreator::increment());
let state = store.get_state();
println!("state: {}", state);
assert_eq!(state, 2);
store.dispatch(ActionCreator::decrement());
store.dispatch(ActionCreator::decrement());
let state = store.get_state();
println!("state: {}", state);
assert_eq!(state, 0);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment