In e.g. Python if we have a set we can call set.pop() and it will remove a value from the set and return it.
I'm working through an algorithms question in JS where I need to do this. But there doesn't seem to be a way to, as the set.delete() function expects a value, and I don't have access to the values. Is there an easy work around?
You can iterate over the values. (It would be faster than converting it to an array.)
function deleteRandomElement(set) {
if (set.size > 0) {
const randomIndex = Math.floor(Math.random()*set.size);
let i = 0;
for(const value of set) {
if(i === randomIndex) {
set.delete(value);
break;
}
i++;
}
}
}