How to get a random item from es6 Map or Set

I have a project that uses arrays of objects that I am going to move to es6 Sets or Maps.

I need to quickly get a random element from them (obviously trivial for my current arrays). How should I do it?

+4
source share
1 answer

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.

/, .

// get random item from a Set
function getRandomItem(set) {
    let items = Array.from(set);
    return items[Math.floor(Math.random() * items.length)];
}

, Set, Map :

// returns random key from Set or Map
function getRandomKey(collection) {
    let keys = Array.from(collection.keys());
    return keys[Math.floor(Math.random() * keys.length)];
}

, , , , , .


Map, Set , , .size, , N- . , /2 .

// returns random key from Set or Map
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;
        }
    }
}
+4

Source: https://habr.com/ru/post/1672068/


All Articles