Checking if every array element matches a condition
JavaScript
Read fire tipGetting a random number is fun, but it’s not “getting a random element from an array” fun. I don’t know why you’d want to do this, but you can.
// get a random element from the given array
const sample = array => array[Math.floor(Math.random() * array.length)]
// every time we use `sample`, it returns a random element
sample([17, 6, 22, 13, 9]) // ⇒ 13 (maybe)
sample([17, 6, 22, 13, 9]) // ⇒ 6 (maybe)
sample([17, 6, 22, 13, 9]) // ⇒ 6 (maybe)
sample([17, 6, 22, 13, 9]) // ⇒ 17 (maybe)
Syntactic sugar on the Array prototype’s map function and type constructors being functions allow us to quickly map values from one type to another.