I'm attempting to test feature to only push to this array 10% of the time, I've come up with a solution that works but is there a more dynamic way of handling this?
This is what I came up with:
const random = []
const randomNumber = Math.round(Math.random() * 9);
console.log(randomNumber)
if (randomNumber === 5) {
random.push({
title: "testing"
})
console.log(random, 'testing push')
} else {
console.log('not this time')
}
I'm selecting 10 possibly numbers, if the number equals 5 then push to the array, if not don't. This would make it a 1/10 chance if it pushing it to the array.
Is it possible to create a more dynamic solution of saying 10% of the time push the object to the array?
I would say you can simplify your formula:
const percentage=10;
if (Math.random() <== percentage/100){
//Should be executed 10% of the time
}