I have been working on implementing a shuffle/unshuffle feature in my Angular application. The concept is simple - there's a single button that, when clicked, will either shuffle an array and return the shuffled order, or if the array has already been shuffled, it will revert back to the original order by returning a clone of the original array.
My problem lies in figuring out how to display the original order clone in the view.
For reference, here is a Fiddle where you can see the code in action: http://jsfiddle.net/nf6j1qvz/
Below is the function code for this functionality:
$scope.shuffleThis = function(array) {
if(!$scope.isShuffled){
$scope.isShuffled = true;
$scope.unshuffled = array.slice(0);
var m = array.length, t, i;
// While there remain elements to shuffle
while (m) {
// Pick a remaining element…
i = Math.floor(Math.random() * m--);
// And swap it with the current element.
t = array[m];
array[m] = array[i];
array[i] = t;
}
return array;
}else{
console.log('unshuffling');
$scope.isShuffled = false;
array = $scope.unshuffled;
return array;
}
}