Logo

Programming-Idioms

History of Idiom 11 > diff from v81 to v82

Edit summary for version 82 by gumbo59:
New JS implementation by user [gumbo59]

Version 81

2019-09-29, 17:34:15

Version 82

2019-10-01, 16:19:23

Idiom #11 Pick a random element from a list

List x must be non-empty.

Illustration

Idiom #11 Pick a random element from a list

List x must be non-empty.

Illustration
Extra Keywords
choose
Extra Keywords
choose
Code
const x = [1, 'two', 3, 4, 'five', 'six', 7, 8, 'nine' ];

const randomElement = x[~~(Math.random() * x.length)];
Comments bubble
• 'x' is the list
• 'randomElement' generates the random element

• ~~ is just a faster way to call Math.floor()

• Math.random() gives a random number between 0 and 1. Here we multiply that by the length of the list to be sure the index exists