Last active
October 27, 2017 03:48
-
-
Save cubicleWar/7f9702850d3f9a7e6778 to your computer and use it in GitHub Desktop.
AngularJS filter for performing a Fisher-Yates shuffle of an array.
This file contains hidden or 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
// | |
// Performs a Fisher-Yates shuffle of an array | |
// | |
// @param input An array of items to shuffle | |
// | |
angular.module('nd.filters').filter('shuffle', function() { | |
function shuffle(input) | |
{ | |
var out = []; | |
// Perform shallow copy of the array | |
angular.forEach(input, function(value) { | |
out.push(value); | |
}); | |
// Perform Fisher-Yates shuffle | |
for (var i = input.length - 1; i > 0; i--) | |
{ | |
var j = Math.floor(Math.random() * (i + 1)), | |
temp = out[i]; | |
out[i] = out[j]; | |
out[j] = temp; | |
} | |
return out; | |
} | |
return shuffle; | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment