Skip to content

Instantly share code, notes, and snippets.

@cowboy
Created December 1, 2011 17:22
Show Gist options
  • Save cowboy/1418349 to your computer and use it in GitHub Desktop.
Save cowboy/1418349 to your computer and use it in GitHub Desktop.
JavaScript: Silly Array Shuffle
// Array.indexed(4) returns [0, 1, 2, 3]
Array.indexed = function(n) {
var result = [];
while (n--) {
result[n] = n;
}
return result;
};
// Shuffle an array in a not too efficient way.
Array.prototype.shuffle = function() {
return this.map(function(item) {
return {value: item, toString: function() { return +this; }.bind(Math.random())};
}).sort().map(function(item) {
return item.value;
});
};
Array.indexed(5).shuffle(); // something like [2, 3, 0, 1, 4]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment