Skip to content

Instantly share code, notes, and snippets.

@z2015
Created May 2, 2016 02:44
Show Gist options
  • Select an option

  • Save z2015/9879ea516c29df7f2cacdae40eafa93b to your computer and use it in GitHub Desktop.

Select an option

Save z2015/9879ea516c29df7f2cacdae40eafa93b to your computer and use it in GitHub Desktop.
Redux: Writing a Todo List Reducer (Toggling a Todo)
const todos = (state=[], action) => {
switch (action.type) {
case 'ADD_TODO':
return [
...state,
{
id: action.id,
text: action.text,
completed: false
}
];
case 'TOGGLE_TODO':
return state.map(
todo => {
if (todo.id != action.id){
return todo;
}
return {
...todo,
completed: !todo.completed
};
}
)
default:
return state;
}
};
const testAddTodo = () => {
const stateBefore = [];
const action = {
type: 'ADD_TODO',
id: 0,
text: 'Learn Redux'
};
const stateAfter = [
{
id: 0,
text: 'Learn Redux',
completed: false
}
];
deepFreeze(stateBefore);
deepFreeze(stateAfter);
expect (
todos(stateBefore, action)
).toEqual(stateAfter);
};
const testToggleTodo = ()=> {
const stateBefore = [
{
id: 0,
text: 'Learn Redux',
completed: false
},
{
id: 1,
text: 'Go shopping',
completed: false
}
];
const action = {
type: 'TOGGLE_TODO',
id: 1
};
const stateAfter = [
{
id: 0,
text: 'Learn Redux',
completed: false
},
{
id: 1,
text: 'Go shopping',
completed: true
}
];
deepFreeze(stateBefore);
deepFreeze(stateAfter);
expect(
todos(stateBefore, action)
).toEqual(stateAfter);
};
testAddTodo();
testToggleTodo();
console.log('Passed');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment