Would like to reduce the amount of random commands in the code and make it flow better?

function generaterandommessage(){

const sign = ['Aries', 'Taurus', 'Gemini', 'Cancer', 'Leo', 'Virgo', 'Libra', 'Scorpio', 'Sagittarius', 'Capricorn', 'Aquarius', 'Pisces'],
fortune = ['awful', 'terrible', 'bad', 'good', 'great', 'brilliant'],
advice = ['going outside', 'driving', 'seeing others', 'cooking', 'drinking', 'spoiling yourself']

console.log(sign[Math.floor(Math.random() * sign.length)]+' is your sign')
console.log('You will have a '+fortune[Math.floor(Math.random() * fortune.length)]+' day')
console.log('I advice against '+advice[Math.floor(Math.random() * advice.length)])

}

generaterandommessage()

I simply have three arrays and in the strings I access each array individually and randomly pick one based one the length of the array so you can add and remove items in the array without it breaking. but I feel it has too many calls to the random command. I hope can anyone make it flow better. the code is in javascript.

You could create a function that does the random part, for example:

const getRandom = (arrLength) => calc here with the math.floor etc;

And you just call to that function with the correct parameters!

thanks. it is working and looks a lot better.

1 Like