Skip to content

Instantly share code, notes, and snippets.

@baetheus
Last active March 20, 2020 19:23
Show Gist options
  • Select an option

  • Save baetheus/7bd3a57d4503f5272a232ae20526d226 to your computer and use it in GitHub Desktop.

Select an option

Save baetheus/7bd3a57d4503f5272a232ae20526d226 to your computer and use it in GitHub Desktop.
Rust Store
Print Listener: [1, 2]
SHOULD ONLY HAPPEN ONCE: [1, 2]
Print Listener: [1, 2, 1]
Print Listener: [1, 2, 1, 2]
Print Listener: [1, 2, 1, 2, 3]
Print Listener: [1, 2, 1, 2, 3, 4]
Final State: [1, 2, 1, 2, 3, 4]
struct Store<S: Clone, A> {
state: S,
reducers: Vec<fn(S, &A) -> S>,
listeners: Vec<fn(&S) -> ()>,
}
impl<S: Clone, A> Store<S, A> {
fn new(state: S) -> Self {
Store::<S, A> {
state,
reducers: Vec::new(),
listeners: Vec::new(),
}
}
fn get(&self) -> S {
self.state.clone()
}
fn add_reducer(mut self, func: fn(S, &A) -> S) -> Self {
self.reducers.push(func);
self
}
fn remove_reducer(mut self, func: fn(S, &A) -> S) -> Self {
if let Some(index) = self
.reducers
.iter()
.position(|i| *i as usize == func as usize)
{
self.reducers.remove(index);
}
self
}
fn add_listener(mut self, func: fn(&S) -> ()) -> Self {
func(&self.state);
self.listeners.push(func);
self
}
fn remove_listener(mut self, func: fn(&S) -> ()) -> Self {
if let Some(index) = self
.listeners
.iter()
.position(|i| *i as usize == func as usize)
// This may be incorrect
{
self.listeners.remove(index);
}
self
}
fn dispatch(mut self, action: A) -> Self {
for reducer in &self.reducers {
self.state = reducer(self.state, &action);
}
for listener in &self.listeners {
listener(&self.state);
}
self
}
}
enum Actions {
Add(i32),
Reset,
}
fn main() {
let add_reducer = |mut s: Vec<i32>, a: &Actions| {
if let Actions::Add(value) = a {
s.push(*value);
}
s
};
let drop_reducer = |s: Vec<_>, _: &Actions| {
println!("THIS SHOULD NOT SHOW UP");
s
};
let print_listener = |s: &Vec<i32>| println!("Print Listener: {:?}", s);
let print_listener_remove = |s: &Vec<i32>| println!("SHOULD ONLY HAPPEN ONCE: {:?}", s);
let my_struct = Store::new(vec![1, 2])
.add_reducer(add_reducer)
.add_reducer(drop_reducer)
.remove_reducer(drop_reducer)
.add_listener(print_listener)
.add_listener(print_listener_remove)
.remove_listener(print_listener_remove)
.dispatch(Actions::Add(1))
.dispatch(Actions::Add(2))
.dispatch(Actions::Add(3))
.dispatch(Actions::Add(4));
println!("Final State: {:?}", my_struct.get());
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment