Skip to content

Instantly share code, notes, and snippets.

@jermspeaks
Created November 2, 2015 23:29
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 jermspeaks/28f711cc436f446312e5 to your computer and use it in GitHub Desktop.
Save jermspeaks/28f711cc436f446312e5 to your computer and use it in GitHub Desktop.
Todo reducer
import * as types from '../constants/ActionTypes'
const initialState = [
{
text: 'Use Redux',
completed: false,
id: 0
}
]
export default function todos(state = initialState, action) {
switch (action.type) {
case types.ADD_TODO:
return [
{
id: state.reduce((maxId, todo) => Math.max(todo.id, maxId), -1) + 1,
completed: false,
text: action.text
},
...state
]
case types.DELETE_TODO:
return state.filter(todo =>
todo.id !== action.id
)
case types.EDIT_TODO:
return state.map(todo =>
todo.id === action.id ?
Object.assign({}, todo, { text: action.text }) :
todo
)
case types.COMPLETE_TODO:
return state.map(todo =>
todo.id === action.id ?
Object.assign({}, todo, { completed: !todo.completed }) :
todo
)
case types.COMPLETE_ALL:
const areAllMarked = state.every(todo => todo.completed)
return state.map(todo => Object.assign({}, todo, {
completed: !areAllMarked
}))
case types.CLEAR_COMPLETED:
return state.filter(todo => todo.completed === false)
default:
return state
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment