Skip to content

Instantly share code, notes, and snippets.

@alexeyraspopov
Last active August 29, 2015 14:23
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alexeyraspopov/5a877a2cc918a040244e to your computer and use it in GitHub Desktop.
Save alexeyraspopov/5a877a2cc918a040244e to your computer and use it in GitHub Desktop.
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 }));
@jonrh
Copy link

jonrh commented Jun 24, 2015

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!

@briandipalma
Copy link

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