Using dataview to select a random from a specified folder improved code

Inspired by the user webinspect from his answer to this particular issue.
I stumbled upon this same issue (the need for pulling RANDOM notes from a particular folder) and webinspect provided a great answer, however one issue was that the output had duplicates, so I improved it by not allowing duplicates and decided to share it incase anyone is facing the same issue.

let docs = dv.pages('"Foldername"'); 
let numberToReturn = 5; 
var randos = getUniqueRandos(docs, numberToReturn); 
dv.list(randos); 
	
function getUniqueRandos(list, itemNum) { 
    if (itemNum > list.length) {
        throw new Error("Cannot request more items than available in the list.");
    }
    
    var randomIndexes = [];
    var uniqueRandos = [];
    
    while (uniqueRandos.length < itemNum) {
        var randomIndex = Math.floor(Math.random() * list.length);
        if (!randomIndexes.includes(randomIndex)) {
            randomIndexes.push(randomIndex);
            uniqueRandos.push(list[randomIndex].file.link);
        }
    }
    
    return uniqueRandos; 
}
4 Likes