Maps and sets are not suitable for random access. They are ordered and their length is known, but they are not indexed for access by order index. Thus, to get the Nth element on a map or set, you need to iterate over it to find that element.
/, .
function getRandomItem(set) {
let items = Array.from(set);
return items[Math.floor(Math.random() * items.length)];
}
, Set, Map :
function getRandomKey(collection) {
let keys = Array.from(collection.keys());
return keys[Math.floor(Math.random() * keys.length)];
}
, , , , , .
Map, Set , , .size, , N- . , /2 .
function getRandomKey(collection) {
let index = Math.floor(Math.random() * collection.size);
let cntr = 0;
for (let key of collection.keys()) {
if (cntr++ === index) {
return key;
}
}
}