forked from steventhomson/array-generic-shuffle
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathshuffle.js
More file actions
51 lines (42 loc) · 1.32 KB
/
shuffle.js
File metadata and controls
51 lines (42 loc) · 1.32 KB
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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
/**
* Implementation of a non-standard array generic method, shuffle, using the Fisher-Yates algorithm.
*
* Copyright (c) 2014 Steven Thomson
* http://opensource.org/licenses/MIT
*/
(function (global, undefined) {
'use strict';
var Array = global.Array,
Object = global.Object,
TypeError = global.TypeError;
// add standard
if (!Array.prototype.shuffle) {
Array.prototype.shuffle = function () {
var elms, len, idx, tmp;
if (this === null || this === undefined) {
throw new TypeError('this is null or undefined');
}
// convert this to object
elms = Object(this);
// convert length to unsigned 32-bit integer
len = elms.length >>> 0;
// fisher-yates shuffle
while (len) {
idx = Math.random() * len-- | 0;
tmp = elms[len];
elms[len] = elms[idx];
elms[idx] = tmp;
}
return elms;
}
}
// add generic
if (!Array.shuffle) {
var shuffle = Array.prototype.shuffle;
if (typeof shuffle === 'function') {
Array.shuffle = function () {
return shuffle.call.apply(shuffle, arguments);
};
}
}
}(this, void 0));