Last active
August 31, 2017 19:51
-
-
Save hrldcpr/3c5b3d3e2e431dc2e8e6d745be379281 to your computer and use it in GitHub Desktop.
ex-exampda
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// We have some state like: | |
const state1 = { | |
data: { some: 'stuff' }, | |
people: ['blah', 'blah', 'blah'], | |
memberships: [ | |
{ id: 1, roles: [], other: 'stuff' }, | |
{ id: 2, roles: ['client'], more: 'junk' } | |
] | |
}; | |
// We want to be able to add a role to a particular membership (without mutation) (but without ramda): | |
const addRole = (id, role) => (obj) => { | |
const newMemberships = obj.memberships.map((membership) => { | |
if (membership.id == id) { | |
const newRoles = membership.roles.concat(role) | |
return Object.assign({}, membership, {roles: newRoles}) | |
} else { | |
return membership | |
} | |
}) | |
return Object.assign({}, obj, {memberships: newMemberships}) | |
} | |
// For example: | |
addRole(2, 'admin')(state1) | |
// …returns a new object, in which `data`, `people`, and membership id 1 are all the exact same objects as before (not copies): | |
{ | |
data: { some: 'stuff' }, | |
people: ['blah', 'blah', 'blah'], | |
memberships: [ | |
{ id: 1, roles: [], other: 'stuff' }, | |
{ id: 2, roles: ['client', 'admin'], more: 'junk' } | |
] | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment