[code] Simple array randomizer (aka shuffle)
Array randomizer, both non-destructive (by copy) and destructive (in-place). It's quite possibly the shortest way to write a shuffle and I can't believe I didn't realize it until now.
/** non-destructive randomizer **/
function shuffle(arr) {
var r = arr.slice();
return r.sort(function(a,b){
return Math.random()-Math.random();
});
}
/** destructive randomizer **/
function shuffle(a,b){return Math.random()-Math.random();}
// ... then sort in place ...
someArray.sort(shuffle);
The two Math.random calls are really the only thing stopping it from being as fast as a normal sort function. Array.sort is inherently destructive and I wanted to operate on a copy; you can use the in-place shuffle if you don't need the copy. You can also modify the sort function to use properties of a and b like any other sort function.