array-random-item
Version:
Returns a random item from an array.
8 lines (7 loc) • 344 B
JavaScript
module.exports = ari = (array) => {
if (array == null || !Array.isArray(array)) throw new TypeError('expected an array');
if (array.length == 0) throw new Error('empty array given');
if (array.length == 1) return array[0];
let randomElement = array[Math.floor(Math.random() * array.length)];
return randomElement;
};