Skip to content

Instantly share code, notes, and snippets.

@esneko
Last active August 19, 2016 21:43
Show Gist options
  • Save esneko/fa2908b47ae69e7f304e to your computer and use it in GitHub Desktop.
Save esneko/fa2908b47ae69e7f304e to your computer and use it in GitHub Desktop.
Seamless Immutable
export default (state = initialState, action) => {
switch (action.type) {
case ADD_LOAN:
return state.merge({
loans: state.loans.concat([action.val])
})
case EDIT_LOAN:
return state.merge({
loans: state.loans.map((loan, id) =>
id === action.id ? loan.merge({
interest: loan.interest * 2,
term: loan.term + 1
}) :
loan
)
})
case DELETE_LOAN:
return state.loans.filter((loan, id) =>
id !== action.id
)
default:
return state
}
}
export default (state = initialState, action) => {
switch (action.type) {
case ADD_LOAN:
return {
...state,
loans: [...state.loans, action.val]
}
case EDIT_LOAN:
return {
...state,
loans: state.loans.map((loan, id) =>
id === action.id ? {
...loan,
interest: loan.interest * 2,
term: loan.term + 1
} :
loan
)
}
case DELETE_LOAN:
return state.loans.filter((loan, id) =>
id !== action.id
)
default:
return state
}
}
import {ADD, REMOVE, REMOVE_ALL} from './action-types'
import si from 'seamless-immutable'
const add = (state, {app, name, component}) => {
const {[app]: types, ...rest} = state
return si(rest).merge({[app]: {...types, [name]: component}})
}
const remove = (state, {app, name}) => {
const {[app]: { [name]: component, ...types }, ...rest} = state
return si(rest).merge({[app]: types})
}
const removeAll = (state, {app}) => {
const {[app]: types, ...rest} = state
return si(rest)
}
const handlers = {
ADD: add,
REMOVE: remove,
REMOVE_ALL: removeAll
}
export default (state=si({}), {type, ...payload}) => {
return handlers[type] ? handlers[type](state, payload) : state
}

Change property of object

ES6

return {
  ...state,
  [name]: value
}

SI

return state.merge({
  [name]: value
})

Change property of object in array

ES6

return state.map(todo =>
  todo.id === action.id ? {
    ...todo,
    text: action.text
  } :
  todo
)

SI

return state.map(todo =>
  todo.id === action.id ?
    todo.merge({text: action.text}) :
    todo
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment