Create a new random value if the value is in an array

I have a situation where I use a protractor to click a random link on a page. (A lot of). I have an array of links that I don’t want to click, so I want to know when my random link is in this array and generates a new random link.

Here is my working code to click an arbitrary link on a page

var noClickArray = ['link2', 'link3']; // array much bigger than this var parent = this; function() { var links = element.all(by.css('.links')); return links.count().then(function(count) { var randomLink = links.get(Math.floor(Math.random() * count)); randomLink.getText().then(function(text) { parent.selectedLink = text; // used in a different function var containsLink = _.includes(noClickArray, text); }); return randomLink.click(); }); } 

I use lodash to search if randomLink text is in noClickArray , but I don't know how to keep generating random values ​​until the value exists in the array. How can i do this?

+5
source share
2 answers

I think that you too often encounter a problem. I would just filter out the links you don't want to click using filter() :

 function() { var links = element.all(by.css('.links')); links = links.filter(function (link) { return link.getText().then(function(text) { return !_.includes(noClickArray, text); }); }); return links.count().then(function(count) { var randomLink = links.get(Math.floor(Math.random() * count)); return randomLink.click(); }); } 
+5
source

You can simply use the recursive call until you get a link other than black. Thus, you will avoid the cost of obtaining text for all links:

 function() { return element.all(by.css('.links')).then(function clickRandom(links) { // remove a random link from the array of links var link = links.splice(Math.floor(Math.random() * links.length), 1)[0]; return link && link.getText().then(function(text) { if(noClickArray.indexOf(text) === -1) { // if not black listed return link.click(); // click link } return clickRandom(links); // try again }); }); } 
+3
source

All Articles