简体   繁体   中英

Is there an object (or array-like object) with O(1) lookup for bigints as the key/index?

Let's say I have 50,000 objects with a structure like:

{
    hash: bigint
    value: number
    name: string
}

Ideally, I would do something like:

const myArray = [];
for (let item of items) { // where item has a structure like the above object
    myArray[item.hash] = item;
}

But arrays don't allow you do use bigints as array indexes, so that is invalid.

Maps and Sets allow keys to be bigints, but in my case the keys are not unique so those two don't work. Using array.filter() works, but it's much slower than a key or index lookup.

Is there an object that supports non-unique bigints as keys or a way to do an O(1) lookup on such an object?

There is Map for this:

const mymap = new Map();
// ...
mymap.set(item.hash, item);

While object keys are limited to strings (and symbols), Map supports primitive data types for its keys (including BigInt), and object references (irrelevant here). So a Map is preferrable to objects in this case.

You can even use the constructor callback to load the data:

const mymap = new Map(items.map(item => [item.hash, item]));

Now to the point of non-unique keys. If you have nothing else to uniquely identify an item, then there is nothing to uniquely look up either: you cannot get further than to make a scan among the items that have the same key in a (smaller) array associated with that key.

Something like:

// Initialise the arrays
const mymap = new Map(items.map(item => [item.hash, []]));
// Populate them by hash
for (const item of items) map.get(item.hash).push(item);

Here the lookup by hash has good time complexity, but it will give you an array. What next needs to happen with that array will determine the overall complexity.

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