Question

I have an in memory database that is fairly deep, I think, I have found the best implementation of the code, if anyone has a better way to do a double forEach loop in lodash or if I am using it wrong somehow would be great to know.

The Object:

smallDB = {
  user1:{
    permissions:[],
    locations:[
      {ip:'0.0.0.0',messages:[]},
      {ip:'',messages:[]}
    ]
  },
  user2:{
    permissions:[],
    locations:[
      {ip:'0.0.0.0',messages:[]},
      {ip:'0.0.1.0',messages:[{mid:'a unique id','user':'the sender',message:'the text of the message'}]}
    ]
  }
}

sending a message I use:

ld.forEach smallDB, (a)->
  ld.forEach a.locations, (b)->
    b.messages.push {mid,user,message}

I just wanted to make sure this is the best way to add messages into the mini database for all the users in smallDB and in all their locations

Était-ce utile?

La solution

There's one very easy optimization you can do if the objects you create with {mid,user,message} are immutable:

record = {mid,user,message}
ld.forEach smallDB, (a)->
  ld.forEach a.locations, (b)->
    b.messages.push record

If you do this, you save yourself the cost of creating a new object each time you push. Dropping the forEach in favor of using for would also make things faster.

It would be further optimizable by allowing a more direct access to the arrays that you access as b.messages in your original code, but this would complicate addition and removal of users or locations. I don't think is worth it unless proved by profiling that it is not a premature optimization.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top