Skip to content

Instantly share code, notes, and snippets.

@mozkoq
Created March 17, 2017 12:02
Show Gist options
  • Save mozkoq/bb1042e129038923ef887264bface58a to your computer and use it in GitHub Desktop.
Save mozkoq/bb1042e129038923ef887264bface58a to your computer and use it in GitHub Desktop.
yey it work
//xs.filter((el, i) => i != 0)*/
// {
// todos: [
// {
// id: 1,
// text: "first",
// status: "active",
// },
// {
// id: 2,
// text: "second",
// status: "done",
// }
// ],
// filter: "all",
// }
// Action types
const ActionType = {
setTodoText: Symbol(),
toggleTodoStatus: Symbol(),
addTodo: Symbol(),
deleteTodo: Symbol(),
setFilter: Symbol(),
}
// Actions
let nextID = 0
const addTodo = text =>
({ type: ActionType.addTodo, payload: { id: nextID++, text, status: "active" } })
const deleteTodo = id =>
({ type: ActionType.deleteTodo, payload: id })
const toggleTodoStatus = id =>
({ type: ActionType.toggleTodoStatus, payload: { id } })
const setTodoText = (text, id) =>
({ type: ActionType.setTodoText, payload: { text, id } })
const setFilter = filter =>
({ type: ActionType.setFilter, payload: filter })
const state = (state, action) => ({
todos: todos(state.todos, action),
filter: filter(state.filter, action),
})
const filter = (filter = "all", action) => {
switch (action.type) {
case ActionType.setFilter:
return action.payload
default:
return filter
}
}
const todos = (todos = [], action) => {
switch (action.type) {
case ActionType.addTodo:
return [ ...todos, action.payload ]
case ActionType.deleteTodo:
return todos.filter(todo => todo.id !== action.payload)
default:
return todos.map(_todo => todo(_todo, action))
}
}
const todo = (todo = {
id: null,
text: "",
status: "active",
}, action) => {
if (action.payload.id !== todo.id) {
return todo
}
switch (action.type) {
case ActionType.toggleTodoStatus:
return {
...todo,
status: toggleStatus(todo.status),
}
case ActionType.setTodoText:
return { ...todo, text: action.payload.text }
default:
return todo
}
}
const toggleStatus = status => {
switch (status) {
case "done":
return "active"
case "active":
return "done"
}
}
console.log(
[
addTodo("hello"),
addTodo("world"),
setFilter("active"),
toggleTodoStatus(0),
setTodoText("---", 0)
].reduce(state, {})
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment