Last active
December 13, 2022 09:00
Redux c++ implementation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <mapbox/variant.hpp> | |
#include <redux.hpp> | |
struct Increment | |
{ | |
}; | |
struct Decrement | |
{ | |
}; | |
typedef mapbox::util::variant< | |
Increment, | |
Decrement | |
> Action; | |
struct State { | |
int value = 0; | |
}; | |
struct Reducer { | |
const State ¤tState; | |
State operator()(const Increment &) { | |
return State { currentState.value + 1 }; | |
} | |
State operator()(const Decrement &) { | |
return State { currentState.value - 1 }; | |
} | |
}; | |
typedef Redux::Store<Action, State, Reducer> Store; | |
int main() { | |
Store store; | |
store.dispatch(Increment()); | |
store.dispatch(Decrement()); | |
store.dispatch(Increment()); | |
store.dispatch(Increment()); | |
std::cout << store.getState().value << std::endl; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#pragma once | |
#include <mapbox/variant.hpp> | |
#include <functional> | |
#include <vector> | |
namespace Redux { | |
template<typename Action, typename State, typename Reducer> | |
struct Store | |
{ | |
void dispatch(const Action &action) { | |
mState = mapbox::util::apply_visitor(Reducer{ mState }, action); | |
for(const auto &listener : mListeners) { | |
listener(); | |
} | |
} | |
const State &getState() const { | |
return mState; | |
} | |
std::function<void()> subscribe(std::function<void()> listener) { | |
int index = mListeners.size(); | |
mListeners.push_back(listener); | |
return [index, this]() { | |
mListeners.erase(mListeners.begin() + index); | |
}; | |
} | |
private: | |
std::vector<std::function<void()>> mListeners; | |
State mState; | |
}; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// https://github.com/mapbox/variant |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment