Skip to content

Instantly share code, notes, and snippets.

@iliran11
Last active October 2, 2017 21:23
Show Gist options
  • Save iliran11/3f9d3832f48cdd3c88fccdf5de62a572 to your computer and use it in GitHub Desktop.
Save iliran11/3f9d3832f48cdd3c88fccdf5de62a572 to your computer and use it in GitHub Desktop.
// Current Persons Data Structure in Client
const clientData = [{
id: 1,
employed: true
},
{
id: 2,
employed: false
},
{
id: 3,
employed: true
},
{
id: 4,
employed: false
}
]
// Server is sending array of Persons Objects, to be updated against Client.
const serverData = [{
id: 2,
newEmployedStatus: true
},
{
id: 3,
newEmployedStatus: false
},
]
// Update Process complexity of O^2 due to nested loops.
// Very Verbose also.
serverData.forEach((serverPerson) => {
clientPerson = clientData.find((element) => {
return element.id === serverPerson.id
})
clientPerson.employed = serverPerson.newEmployedStatus
})
/** one possible solution - object with accessors
* however - not good enough. it doesn't keep the order of the elements.
*/
const clientDataObject = {
1: {
employed:true
},
2: {
employed:false
},
3: {
employed:true
},
4: {
employed:false
}
}
/** Solution - Map Object */
const clientDataMap = new Map(
[
[1, { employed:true }],
[2, { employed:false }],
[3, { employed:true }],
[4, { employed:false }],
]
)
// Updating the clientData will be with reduced complexity and less verbose:
serverData.forEach((serverPerson)=> {
// this operation is O(1)
// https://stackoverflow.com/questions/33611509/es6-map-and-set-complexity-v8-implementation
clientDataMap.get(serverPerson.id).employed = serverPerson.newEmployedStatus
})
/** Still able to print the persons in ordered fashion: */
clientDataMap.forEach((value, key)=> {
console.log(key + ' = ' + value.employed);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment