1
var lst = [/*List of items*/];
for (var i = 10; i > 0; i--) {
    lst.appendChild(lst[Math.random() * i | 0]);
}

Why would "|" be in a index? Does this function shuffle the list 'lst'?

mdev
  • 25
  • 6
  • 6
    `|` is bitwise OR. It's a "clever" way to truncate the floating-point result of `Math.random() * i` to an integer. – Blorgbeard May 26 '16 at 23:52
  • Possible duplicate of [What does the "|" (single pipe) do in JavaScript?](http://stackoverflow.com/questions/6194950/what-does-the-single-pipe-do-in-javascript) – Martin Gottweis May 26 '16 at 23:53

3 Answers3

8

The bitwise OR operator | converts its input to a 32-bit two-complement number. This is often used for fast rounding towards zero (faster than Math.trunc()):

console.log(1.1 | 0); // 1
console.log(1.9 | 0); // 1
console.log(-1.1 | 0); // -1
console.log(-1.9 | 0); // -1

The expression Math.random() * i | 0 therefore equals Math.trunc(Math.random() * i) and returns pseudo-random integers in the range from 0 to i - 1.

PS: A double bitwise negation ~~ has the same effect. Keep in mind that applying bitwise operators effectively reduces the range of integer operands from Number.MAX_SAFE_INTEGER (2⁵³ - 1) to the maximum 32-bit two-complement (2³¹ - 1).

le_m
  • 19,302
  • 9
  • 64
  • 74
  • There is no `Math.truc()`, perhaps you mean `Math.floor()`? – RobG May 27 '16 at 06:25
  • @RobG Math.trunc() is equivalent to Math.floor() for positive numbers only. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/trunc – le_m May 27 '16 at 09:49
  • *Math.random* does not return negative numbers. I had not seen *Math.trunc* before, I searched for it in the EMCAScript 2015 specification. Perhaps it was not fully loaded. – RobG May 27 '16 at 12:49
1

Math.random() gives you random floating-point in range [0, 1). Multiplying it by i in loop gives you weird values. | 0 gives you integer part of value. Math.floor(Math.random()*n) returns random integer in range [0, n), which seems applicable.

The Node.appendChild() method adds a node to the end of the list of children of a specified parent node.

but

If the given child is a reference to an existing node in the document, appendChild() moves it from its current position to the new position

so you just reshuffle first 10 nodes placing random one at the end of list.

luxusko
  • 11
  • 2
0

Math.random() * N) - Get a random number with Digits and between 0 and N, it can be equal to 0 but cannot be equal to N

Math.random() * N) | 0 - Get a random number without Digits (the digits are being dropped without any condition) the result also would be between 0 and N, it can be equal to 0 but cannot be equal to N

W Kenny
  • 1,855
  • 22
  • 33