Skip to content

Commit ba9905a

Browse files
committed
add random(Array) to get a random element from an array of choices
1 parent 113f54c commit ba9905a

File tree

2 files changed

+32
-4
lines changed

2 files changed

+32
-4
lines changed

src/math/random.js

Lines changed: 25 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -76,16 +76,19 @@ p5.prototype.randomSeed = function(seed) {
7676
* If no argument is given, returns a random number from 0
7777
* up to (but not including) 1.
7878
*
79-
* If one argument is given, returns a random number from 0 up to
80-
* (but not including) the number.
79+
* If one argument is given and it is a number, returns a random number from 0
80+
* up to (but not including) the number.
81+
*
82+
* If one argument is given and it is an array, returns a random element from
83+
* that array.
8184
*
8285
* If two arguments are given, returns a random number from the
8386
* first argument up to (but not including) the second argument.
8487
*
8588
* @method random
8689
* @param {Number} [min] the lower bound (inclusive)
8790
* @param {Number} [max] the upper bound (exclusive)
88-
* @return {Number} the random number
91+
* @return {Number|Object} the random number or a random element in choices
8992
* @example
9093
* <div>
9194
* <code>
@@ -112,6 +115,20 @@ p5.prototype.randomSeed = function(seed) {
112115
* text(words[index],10,50); // Displays one of the four words
113116
* </code>
114117
* </div>
118+
* <div>
119+
* <code>
120+
* // Get a random element from an array
121+
* var words = [ "apple", "bear", "cat", "dog" ];
122+
* var word = random(words); // select random word
123+
* text(word,10,50); // Displays one of the four words
124+
* </code>
125+
* </div>
126+
*/
127+
/**
128+
* @method random
129+
* @param {Array} choices the array to choose from
130+
* @return {Object} the random element from the array
131+
* @example
115132
*/
116133
p5.prototype.random = function (min, max) {
117134

@@ -127,7 +144,11 @@ p5.prototype.random = function (min, max) {
127144
return rand;
128145
} else
129146
if (arguments.length === 1) {
130-
return rand * min;
147+
if (arguments[0] instanceof Array) {
148+
return arguments[0][Math.floor(rand * arguments[0].length)];
149+
} else {
150+
return rand * min;
151+
}
131152
} else {
132153
if (min > max) {
133154
var tmp = min;

test/unit/math/random.js

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -56,6 +56,13 @@ suite('Random', function() {
5656
assert.isTrue(result < 10);
5757
});
5858
});
59+
suite('random(["apple", "pear", "orange", "grape"])', function() {
60+
test('should return a fruit', function() {
61+
var fruits = ['apple', 'pear', 'orange', 'grape'];
62+
result = random(fruits);
63+
assert.include(fruits, result);
64+
});
65+
});
5966
});
6067

6168
});

0 commit comments

Comments
 (0)