Javascript - sequencial array-like object -


there tasks adding items shopping cart. if cart array, take o(n) retrieve item id. o(1) using objects, not guarantee have inserting order.

so there elegant way have fast lookup object while maintaining inserting order?

i've typically done having array and object both reference same object. e.g.:

var thingies = []; var thingiesbyid = object.create(null); 

when adding "thingy":

thingies.push(thingy); thingiesbyid[thingy.id] = thingy; 

example:

var thingies = [];  var thingiesbyid = object.create(null);    function addthingy(thingy) {      thingies.push(thingy);      thingiesbyid[thingy.id] = thingy;  }    // note intentionally not adding them in id order  addthingy({id:3, name: "thingy 3"});  addthingy({id:1, name: "thingy 1"});  addthingy({id:2, name: "thingy 2"});    thingies.foreach(function(thingy) {      console.log(thingy.id + ": " + thingy.name);  });


es2015+'s maps maintain insertion order , provide iteration semantics follow order. you'll want test lookup speed on get need be.

example:

const thingies = new map();    function addthingy(thingy) {      thingies.set(thingy.id, thingy);  }    // note intentionally not adding them in id order  addthingy({id:3, name: "thingy 3"});  addthingy({id:1, name: "thingy 1"});  addthingy({id:2, name: "thingy 2"});    (const thingy of thingies.values()) {      console.log(thingy.id + ": " + thingy.name);  }


Comments

Popular posts from this blog

Is there a better way to structure post methods in Class Based Views -

performance - Why is XCHG reg, reg a 3 micro-op instruction on modern Intel architectures? -

jquery - Responsive Navbar with Sub Navbar -