Efficiently Find An Item In A Set
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
Solution 1:
You have has method on Set to find existence of value.
let set = newSet([1,2,4,5,6,7])
console.log(set.has(2))
console.log(set.has(10))
Solution 2:
Use a Map instead with the id (unique identifier) as the key:
const items = [{ id: 1 }, { id: 2 }, { id: 3 }]
const itemsMap = newMap(items.map(o => [o.id, o]))
const item = itemsMap.get(1)
console.log(item)
Solution 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);
Post a Comment for "Efficiently Find An Item In A Set"