Skip to content

Instantly share code, notes, and snippets.

@ryanmorr
Last active March 29, 2024 00:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ryanmorr/be4e1375a423017b870c4fa9317a6620 to your computer and use it in GitHub Desktop.
Save ryanmorr/be4e1375a423017b870c4fa9317a6620 to your computer and use it in GitHub Desktop.
Simple redux-style state machine via a generator function
function *stateGenerator(state, reducer) {
let action;
while (true) {
if (action) {
state = reducer(state, action);
}
action = yield state;
}
}
// Usage:
const iter = stateGenerator({count: 0}, (state, action) => {
switch (action.type) {
case 'increment':
return {count: state.count + 1};
case 'decrement':
return {count: state.count - 1};
default:
return state;
}
});
iter.next(); //=> {value: {count: 0}, done: false}
iter.next({type: 'increment'}); //=> {value: {count: 1}, done: false}
iter.next({type: 'increment'}); //=> {value: {count: 2}, done: false}
iter.next({type: 'decrement'}); //=> {value: {count: 1}, done: false}
iter.next({type: 'increment'}); //=> {value: {count: 2}, done: false}
iter.next({type: 'increment'}); //=> {value: {count: 3}, done: false}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment