Efficiently find an item in a Set [duplicate]

扶醉桌前 提交于 2020-01-06 06:54:44

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!