Last active
August 29, 2015 14:23
-
-
Save alexeyraspopov/5a877a2cc918a040244e to your computer and use it in GitHub Desktop.
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
const INCREMENT = 'INCREMENT', DECREMENT = 'DECREMENT'; | |
function reducer(state, action) { | |
switch (action.type) { | |
case INCREMENT: | |
return state + 1; | |
case DECREMENT: | |
return state - 1; | |
} | |
} | |
function* states(reducer, initialState) { | |
while (true) { | |
// yield returns an argument that was passed in .next() | |
initialState = reducer(initialState, yield initialState); | |
} | |
} | |
var appState = states(reducer, 0); | |
// first .next() call ignores passed arguments | |
// (or I didn't use generator correctly) | |
console.log(appState.next()); | |
// each time iterator will update the state with provided action and return new state | |
console.log(appState.next({ type: INCREMENT })); | |
console.log(appState.next({ type: INCREMENT })); | |
console.log(appState.next({ type: INCREMENT })); | |
console.log(appState.next({ type: DECREMENT })); |
21 - 22 is fine, that's the way generators are meant to work, it will run the generator to the first yield
and then pause it. Next time you call next
it picks up from there hence a passed in argument now being used.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I tried to find a bit of info about the issue commented in line 21 - 22 but came up empty handed. I haven't used generators myself yet and am unaware what the right thing to do is. Thanks again for the English comments, they helped a lot. Very interesting and clean idea!