forked from angus-c/just
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
36 lines (34 loc) · 884 Bytes
/
Copy pathindex.js
File metadata and controls
36 lines (34 loc) · 884 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
module.exports = shuffle;
/*
shuffle([1, 2, 3]);
// array with original elements randomly sorted
shuffle([1, 2, 3], {shuffleAll: true});
// array with original elements randomly sorted and all in a new position
shuffle([1]); // [1]
shuffle(); // throws
shuffle(undefined); // throws
shuffle(null); // throws
shuffle({}); // throws
*/
function shuffle(arr, options) {
if (!Array.isArray(arr)) {
throw new Error('expected an array');
}
if (arr.length < 2) {
return arr;
}
var shuffleAll = options && options.shuffleAll;
var result = arr.slice();
var i = arr.length, rand, temp;
while (--i > 0) {
do {
rand = Math.floor(Math.random() * (i + 1));
} while (shuffleAll && rand == i);
if (!shuffleAll || rand != i) {
temp = result[i];
result[i] = result[rand];
result[rand] = temp;
}
}
return result;
}