问题
if I need to find an object in a Set. The set does not contain a natural key to use as an index, so I can't use Map. There are several different types of predicates used to search the Set. It seems inefficient to do
const items = Array.from( mySet )
const found = items.find( item => someTest( item ) )
Unless there's black magic in the optimiser, it seems like it will enumerate twice. I know it exposes an iterator interface, but the Array.prototype.find interface is much more concise than using a for...of loop with a break statement.
Is there a better way?
回答1:
You have has method on Set to find existence of value.
let set = new Set([1,2,4,5,6,7])
console.log(set.has(2))
console.log(set.has(10))
回答2:
Use a Map instead with the id (unique identifier) as the key:
const items = [{ id: 1 }, { id: 2 }, { id: 3 }]
const itemsMap = new Map(items.map(o => [o.id, o]))
const item = itemsMap.get(1)
console.log(item)
回答3:
Sets implement the iterator interface, so you should be able to iterate them looking for your particular item. It will not be as nice and declarative as using a find with an hig order function, with will be much more efficient. You can of course encapsulate that logic to make it much nicer
const findInSet = (pred, set) => {
for (let item of set) if(pred(item)) return item;
}
const item = findInSet(someTest, mySet);
来源:https://stackoverflow.com/questions/55077938/efficiently-find-an-item-in-a-set