Skip to content

Instantly share code, notes, and snippets.

@BTMPL
Last active December 17, 2016 21:09
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 BTMPL/d890f0c38e45c6a984f5b3604e4d0faf to your computer and use it in GitHub Desktop.
Save BTMPL/d890f0c38e45c6a984f5b3604e4d0faf to your computer and use it in GitHub Desktop.
ImmutableJS for dummies
function reduce(state = Immutable.fromJS({
items: {
values: []
}
}), action = null) {
if(action) {
switch(action.type) {
case "ADD":
return state.updateIn(['items','values'], (data) => data.push(action.payload));
case "REMOVE":
return state.updateIn(['items','values'], (data) => data.delete(data.findKey((item) => item.id === action.payload.id)))
case "UPDATE":
return state.updateIn(['items','values'], (data) => data.update(data.findKey((item) => item.id === action.payload.id), (item) => Object.assign({}, item, action.payload)))
}
}
return state;
}
let state;
state = reduce(state, { type: "ADD", payload: { id: 1, value: Math.random() }});
state = reduce(state, { type: "ADD", payload: { id: 2, value: Math.random() }});
state = reduce(state, { type: "ADD", payload: { id: 3, value: Math.random() }});
state = reduce(state, { type: "UPDATE", payload: { id: 2, value: -1 }});
state = reduce(state, { type: "REMOVE", payload: { id: 3 }});
state.getIn(['items','values']).map(i => console.log(i.value));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment