Last active
May 28, 2017 21:24
-
-
Save stockwellb/b27c29d655866d6abd03fd6c849b71df to your computer and use it in GitHub Desktop.
Immutable Fab Four
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
let states = []; | |
const initialState = { | |
ids: [], | |
entities: {} | |
} | |
states = [...states, initialState] | |
// add john | |
const john = {id: 1, name: 'John Lennon'}; | |
const solo = { | |
ids: [...initialState.ids, john.id], | |
entities: Object.assign({}, initialState.entities, {[john.id]: john}) | |
} | |
states = [...states, solo]; | |
// add paul, george and ringo | |
const others = [ | |
{id: 2, name: 'Paul McCartney'}, | |
{id: 3, name: 'George Harrison'}, | |
{id: 4, name: 'Ringo Starr'} | |
]; | |
let newIds = others.map(x => x.id); | |
let newEntities = others.reduce((acc, member) => { | |
return Object.assign(acc, {[member.id]: member}); | |
},{}) | |
const fabFour = { | |
ids: [...solo.ids, ...newIds], | |
entities: Object.assign({}, solo.entities, newEntities) | |
}; | |
states = [...states, fabFour]; | |
//add billy | |
const billy = {id: 5, name: 'Billy Preston'}; | |
const fabFourV1 = { | |
ids: [...fabFour.ids, billy.id], | |
entities: Object.assign({}, fabFour.entities, {[billy.id]: billy}) | |
} | |
states = [...states, fabFourV1]; | |
//remove billy and replace him with eric | |
const eric = {id: 6, name: 'Eric Clapton'}; | |
newIds = fabFourV1.ids.filter(x => x != billy.id) | |
newEntities = newIds.map(id => fabFourV1.entities[id]).reduce((acc, member) => { | |
return Object.assign(acc, {[member.id]: member}); | |
},{}); | |
fabFourV2 = { | |
ids: [...newIds, eric.id], | |
entities: Object.assign({}, newEntities, {[eric.id]: eric}) | |
} | |
states = [...states, fabFourV2]; | |
for (var i = 0, len = states.length; i < len; i++) { | |
console.log(states[i].ids.map(id => states[i].entities[id].name)); | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment