I'm working on the FreeCodeCamp 'Random Quote Machine' front end library project using React JSX, which was working fine with the exception that it frequently produced the same quote two or three times in a row. This was not a good thing for a user to exprience.
Looking into Math.random()
I quickly realisded that this was quite normal - two or three repeats of the same number in a row. This is the code I had in a React method called getQuote:
// get new quote from array
getQuote() {
let x = Math.floor(Math.random() * quotes.length);
{console.log("random num = ", x)};
this.setState(quotes[x]
);
This meant that I had to write a method of producing a random number that wasn't the same as the last. Which, thanks to the quality content on this site and input from @Etienne Martin I found pretty quickly:
Most of the answers in this thread are over complicated.
Here's a concise example of how I would do that:
function getNumber(){
return (getNumber.number = Math.floor(Math.random() * (4 + 1))) === getNumber.lastNumber ? getNumber() : getNumber.lastNumber = getNumber.number; }
console.log(getNumber()); // Generates a random number between 0 and 4
Live example: https://jsfiddle.net/menv0tur/3/ share edit flag edited Apr 22 '17 at 16:25 answered Apr 20 '17 at 19:35
This allowed me to write my own method:
getQuote() {
const randNum = () => {
return (randNum.x = Math.floor(Math.random() * (quotes.length))) === randNum.y ? randNum() : randNum.y = randNum.x;
}
this.setState(quotes[randNum()])
}
My problem is; I don't fully understand it. Specifically getNumber.number
it looks as though it is using dot notation to access a key value of our function getNumber()
. I have never seen this before. As you can see in my re-write I defined the function name randNum()
and I'm using randNum.x and randNum.y
instead of getNumber.number
and getNumber.lastNumber
.
Could someone kindly enlighten me as to exactly what we are doing here?
Many thanks in advance.