re: Write a simple but impactful script VIEW POST

TOP OF THREAD FULL DISCUSSION
re: Hey, this is nice. Can you please explain the function you passed to sort()?
 

Sure, we were supposed to sort randomly and sort() expects a function that compares two values and returns >0 if greater 0 if equal and <0 if lesser, so,

  • For the random order, I used Math.random that returns a value between 0 and 1

  • To be sure that it can return a negative number I multiplied the random times number * 2 so:

    • If Math.random < 0.5 it will be positive
    • If Math.random == 0.5 it will be zero
    • If Math.random > 0.5 it will be negative

However, since we have three possible cases it could be better to do something like:


.sort(number => number - Math.floor(Math.random() * number * 3));

That way there is a 33.33% of probability for each case.

code of conduct - report abuse