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 map
s 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
Post a Comment