简体   繁体   中英

Javascript - sequencial array-like object

There are often some tasks like adding items into shopping cart. If the cart is an array, it will take O(n) to retrieve an item by id. It is O(1) using objects, but it then does not guarantee to have the inserting order.

So is there an elegant way to have fast lookup object while maintaining the inserting order?

I've typically done this by having an array and an object that both reference the same object. Eg:

var thingies = [];
var thingiesById = Object.create(null);

when adding a "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 and provide iteration semantics that follow that order. You'll want to test that lookup speed on get is as good as you need it to 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"}); for (const thingy of thingies.values()) { console.log(thingy.id + ": " + thingy.name); } 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM