Last active
March 29, 2024 00:30
-
-
Save ryanmorr/be4e1375a423017b870c4fa9317a6620 to your computer and use it in GitHub Desktop.
Simple redux-style state machine via a generator function
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
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