Created
December 1, 2011 17:22
-
-
Save cowboy/1418349 to your computer and use it in GitHub Desktop.
JavaScript: Silly Array Shuffle
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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